Android自定义View实现心形图案

本文实例为大家分享了Android自定义View实现心形的具体代码,供大家参考,具体内容如下
通过继承View实现的?形

在绘制心形需要Path类中的两个重要方法分别是:moveTo、cubicTo
moveTo 不会进行绘制,只用于移动移动画笔。
lineTo 用于进行直线绘制。
quadTo 用于绘制圆滑曲线,即贝塞尔曲线。
cubicTo 同样是用来实现贝塞尔曲线的。
具体实现:

public class HeartView extends View {private int mMeasureWidth; private int mWidthMode; private int mMeasureHeight; private int mHeightMode; private Paint paint; public HeartView(Context context) {super(context); } public HeartView(Context context, AttributeSet attrs) {super(context, attrs); paint = new Paint(); //实例画笔paint.setAntiAlias(true); //抗锯齿paint.setStrokeWidth(2); //画笔宽度paint.setColor(Color.RED); //画笔颜色paint.setStyle(Paint.Style.FILL); //画笔样式} /*** 测量*/@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec); mWidthMode = MeasureSpec.getMode(widthMeasureSpec); mHeightMode = MeasureSpec.getMode(heightMeasureSpec); mMeasureWidth = MeasureSpec.getSize(widthMeasureSpec); mMeasureHeight = MeasureSpec.getSize(heightMeasureSpec); if (mWidthMode == MeasureSpec.AT_MOST && mHeightMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, 200); } else if (mWidthMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, mMeasureHeight); } else if (mHeightMode == MeasureSpec.AT_MOST) {setMeasuredDimension(mMeasureWidth, 200); } else {setMeasuredDimension(mMeasureWidth, mMeasureHeight); }} @Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas); int width = getWidth(); //获取屏幕宽int height = getHeight(); //获取屏幕高 /***绘制心形*///左半面Path path = new Path(); path.moveTo(width / 2, height / 4); path.cubicTo((width * 6) / 7, height / 9, (width * 12) / 13, (height * 2) / 5, width / 2, (height * 7) / 12); canvas.drawPath(path, paint); //右半面Path path2 = new Path(); path2.moveTo(width / 2, height / 4); path2.cubicTo(width / 7, height / 9, width / 13, (height * 2) / 5, width / 2, (height * 7) / 12); canvas.drawPath(path2, paint); }}

在布局中引入一下

实现效果:
Android自定义View实现心形图案
文章图片

【Android自定义View实现心形图案】以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

    推荐阅读