-
Notifications
You must be signed in to change notification settings - Fork 91
CustomView
sloop edited this page Jun 6, 2016
·
1 revision
自定义View基类,如果你的自定义View继承这个类则能自动获取到View大小与一个默认到Paint,可以帮助你节省部分代码,示例如下:
public class MyView extends View {
private int mWidth;
private int mHeight;
private Paint mPaint;
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// 初始化画笔
mPaint.setColor(Color.GRAY);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 获取View宽高与画笔并根据此绘制内容
canvas.translate(mWidth / 2, mHeight / 2);
canvas.drawCircle(0,0,100,mPaint);
}
}
public class MyView extends CustomView {
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// 初始化画笔
mDefaultTextPaint.setColor(Color.GRAY);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 获取View宽高与画笔并根据此绘制内容
canvas.translate(mViewWidth / 2, mViewHeight / 2);
canvas.drawCircle(0,0,100,mDeafultPaint);
}
}