自定义View之-通过继承View重写onDraw

这种方法主要用于实现一些不规则的效果,继承View 通过重写onDraw方法来实现一些效果,需要自己支持wrap_content,并且padding也要去进行处理。

圆形View的自定义过程

(1).继承View重写onDraw()方法

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //处理padding
    final int paddingLeft = getPaddingLeft();
    final int paddingRight = getPaddingRight();
    final int paddingTop = getPaddingTop();
    final int paddingBottom = getPaddingBottom();
    int width = getWidth() - paddingLeft - paddingRight;
    int height = getHeight() - paddingTop - paddingBottom;
    int radius = Math.min(width, height) / 2;
    canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint);
}

(2).重写onMeasure()方法,让View支持wrap_content

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    //支持wrap_content 处理逻辑代码
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(defaultWidth, defaultHeight);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(defaultWidth, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, defaultHeight);
    }
}

(3).添加自定义属性

1.首先需要在values目录下创建xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CircleView">
    <attr name="circle_color" format="color"></attr>
</declare-styleable>
</resources>

2.在View的构造函数中解析自定义属性并作相应处理

 public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);
    mColor = a.getColor(R.styleable.CircleView_circle_color, mColor);
    a.recycle();
    init();
}

3.在布局文件中使用自定义属性

   <com.customview.mryu93.circleview.CircleView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:background="#000000"
    android:padding="10dp"
    app:circle_color="#000080" />

效果

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容