通過繼承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);
}
}
在佈局中引入一下
<com.xxb.cache.weight.HeartView
android:layout_width="match_parent"
android:layout_height="match_parent" />
實現效果: