public class TestView extends View {
public TestView(Context context) {
super(context);
}
public TestView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public TestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public TestView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//父容器宽高
int width = getWidth();
int height = getHeight();
//获取相机边框图片
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.img_scanner);
//图片宽高
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
//确定矩形左边和上边的距离
int strokeWidth = (width-bitmapWidth)/2;
int strokeHeight = (height-bitmapHeight)/2;
RectF rectF = new RectF();
Paint shellPaint = new Paint();
shellPaint.setAntiAlias(true);
/*图片周围的颜色*/
int myColor = this.getResources().getColor(R.color.colorBlack3);
shellPaint.setColor(myColor);
/*设置画笔宽度,中间漏空情况下,画笔宽度=左边宽度或右边宽度或上边宽度或下边宽度
加粗是围绕中间矩形的边向两边平分扩散*/
shellPaint.setStrokeWidth(strokeWidth*2);
//设置画笔的样式(这里设置的是空心矩形)
shellPaint.setStyle(Paint.Style.STROKE);
//根据左上右下的四个点确定空心矩形的位置
rectF.left = strokeWidth;
rectF.top = strokeHeight;
rectF.right = width - strokeWidth;
rectF.bottom = height - strokeHeight;
canvas.drawRect(rectF, shellPaint);
canvas.drawBitmap(bitmap, strokeWidth, strokeHeight, shellPaint);
RectF rectF1 = new RectF();
rectF1.left = 0;
rectF1.right =getWidth();
rectF1.top = 0;
//因为画笔宽度设置成二倍,所以这里需要减去一倍,也就是strokeWidth
rectF1.bottom = strokeHeight-strokeWidth;
Paint paint = new Paint();
paint.setColor(myColor);
canvas.drawRoundRect(rectF1,0,0,paint);
RectF rectF2 = new RectF();
rectF2.left = 0;
rectF2.right =getWidth();
rectF2.top = height-(strokeHeight-strokeWidth);
rectF2.bottom = height;
canvas.drawRoundRect(rectF2,0,0,paint);
}
}