自定义View画圆
程序员文章站
2022-07-13 15:30:18
...
自定义属性建attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ballview">
<attr name="ball_size" format="integer"></attr>
</declare-styleable>
</resources>
自定义View
public class BallView extends View {
//定义画笔
private Paint mPaint;
private int circleR;
private float currentX=100;
private float currentY=100;
public BallView(Context context) {
super(context);
initView();
}
public BallView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initView();
//获取属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ballview);
circleR = typedArray.getInteger(R.styleable.ballview_ball_size, 100);
typedArray.recycle();//回收资源
}
public void initView(){
mPaint=new Paint();
mPaint.setColor(Color.GREEN);
mPaint.setStrokeWidth(10);
mPaint.setStyle(Paint.Style.FILL);
}
//三个构造方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//画球
canvas.drawCircle(currentX,currentY,circleR,mPaint);
}
//触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
currentX = event.getX();
currentY = event.getY();
invalidate();//刷新
break;
}
return true;
}
}
xml代码
<?xml version="1.0" encoding="utf-8"?>
<bawei.com.ballviewdemo.BallView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
app:ball_size=“200”
/>
<bawei.com.ballviewdemo.BallLayout
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”></bawei.com.ballviewdemo.BallLayout>
推荐阅读