Android通过自定义View实现心形(贝塞尔曲线)
16lz
2021-01-26
通过继承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);//画笔样式 } /** * 测量 */ @Override protected 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); } } @Override protected 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 OpenGL ES2.0编程(1)
- Android(安卓)开发之RecyclerView的使用
- Android(安卓)自定义View视图
- Android(安卓)opengl es 2.0怎么学习
- Paint和Color的介绍
- Android实现炫酷播放效果
- 【UI交互效果】android UI效果二: 给选中的图片加边框
- Android使用Canvas绘制圆形进度条效果
- android图像绘制(六)——获取本地图片或拍照图片