在自定义控件中,一种类型就是继承自 View,通过画笔,从无到有画出一个符合需求的控件。在工作中,相机模块中,需要做一个点击后的聚焦框,就是通过继承 View,从无到有画出来的。
实现代码如下:
package cn.zzw.customview.custom.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import cn.zzw.customview.R;
/**
* 聚焦框
*/
public class FocusFrame extends View {
private Paint mPaint;
private Path path;
public FocusFrame(Context context) {
this(context, null);
}
public FocusFrame(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public FocusFrame(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
//初始化画笔
mPaint = new Paint();
//画边框
path = new Path();
/*
Paint.Style.FILL设置只绘制图形内容
Paint.Style.STROKE设置只绘制图形的边
Paint.Style.FILL_AND_STROKE设置都绘制*/
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setColor(getContext().getResources().getColor(R.color.colorAccent));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
path.moveTo(0, 0);
path.lineTo(width, 0);
path.lineTo(width, height);
path.lineTo(0, height);
path.close();
canvas.drawPath(path, mPaint);
//画线
int lineWidth = 30;
int maxWidth = Math.min(width, height);
if (lineWidth * 2 > maxWidth) {
lineWidth = maxWidth / 2;
}
int count = 4;
for (int i = 0; i < count; i++) {
canvas.drawLine(0, height / 2, lineWidth, height / 2, mPaint);
canvas.rotate(360 / count, width / 2, height / 2);
}
}
/**
* 设置颜色.
*/
public void setColor(int color) {
mPaint.setColor(color);
invalidate();
}
}