RectF用法

自定义控件的时候经常会遇到需要画弧线、话矩形。 这就要用到RectF方法。

先解释一下RectF的几个属性

  • RectF.left 矩形左上角的x坐标。
  • RectF.top 矩形左上角的y坐标。
  • RectF.right 矩形右下角的y坐标。
  • RectF.right 矩形右下角的y坐标。
    RectF用法_第1张图片
    使用方法
public class MyView extends View {
     

    private String TAG = "MyView ";

    private int mRadius;
    private int mX;
    private int mY;
    private float mCenterX;
    private float mCenterY;

    private RectF mRectF;

    public MyView (Context context, AttributeSet attrs) {
     
        super(context, attrs);
        Log.i(TAG,"MyView ");
    }

    @Override
    public void draw(Canvas canvas) {
     
        super.draw(canvas);
        Log.i(TAG,"draw");
        
        //RectF设置
        mRectF = new RectF();
        mRectF.left = mCenterX - mRadius;
        mRectF.top =mCenterY - mRadius;
        mRectF.right = mCenterX + mRadius;
        mRectF.bottom = mCenterY + mRadius;

        //矩形画笔
        Paint mRectPaint = new Paint();
        mRectPaint.setColor(Color.BLUE);
        mRectPaint.setStrokeWidth(20);
        mRectPaint.setStyle(Paint.Style.STROKE);
        //画矩形
        canvas.drawRect(mRectF,mRectPaint);

        //圆弧画笔
        Paint mArcPaint = new Paint();
        mArcPaint.setColor(Color.RED);
        mArcPaint.setStrokeWidth(20);
        mArcPaint.setStyle(Paint.Style.STROKE);
        //画圆弧
        //startAngle 圆弧开始位置,从3点钟方向开始
        //sweepAngle 圆弧弧度
        //useCenter ,false为空心圆弧,true为实心(扇形)圆弧
        canvas.drawArc(mRectF,0,180,false,mArcPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
     
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i(TAG,"onSizeChanged ");
        mX = w;
        mY = h;
        mRadius = w/4;
        mCenterX = mX/2;
        mCenterY = mY/2;
    }
}

你可能感兴趣的:(Android开发,android)