Android 自定义控件:继承View

在自定义控件中,一种类型就是继承自 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();
    }
}

效果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值