自己学习自定义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>