气泡样式的自定义View

自己学习自定义View 画了一个简单的自定义View ,做一下笔记。 

public class BubbleView extends View {

    private Paint mPaint;
    private Path path;


    // 默认定义圆角为80 个像素点,后期可以考虑加到属性里
    private int corner = 80;

    public AView(Context context) {
        this(context,null);
    }

    public AView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public AView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BubbleView);
        int color = a.getColor(R.styleable.BubbleView_color,Color.BLUE);
        a.recycle();
        initPaint(color);
    }

    private void initPaint(int color){
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(color);
        path = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        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(150,150); // 这个100 应该是像素
        } else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(150,heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize,150);
        }

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        final int paddingLeft = getPaddingLeft();
        final int paddingRight = getPaddingRight();
        final int paddingTop = getPaddingTop();
        final int paddingBottom = getPaddingBottom();

        int width = getWidth();
        int height = getHeight() - corner*2;

        path.arcTo(0,0,corner*2,corner*2,
                270,-90,false);
        path.lineTo(0,height+corner);
        path.arcTo(0,height,corner*2,height+corner*2,
                180,-90,false);
        path.lineTo(width-corner,height+2*corner);
        path.arcTo(width-corner*2,height,width,height+corner*2,
                90,-90,false);
        path.lineTo(width,0);
        path.lineTo(corner,0);

        canvas.drawPath(path,mPaint);
    }
}

attrs.xml

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值