사용자 정의 View-4 - 다시 쓰기 onDraw

4858 단어

효과도


페이지 코드

public class SouthView extends View {
    private Paint mPaint;
    private int mRadius;
    private int mCirclrRadius;
    private float mDegrees=0;

    public SouthView(Context context) {
        super(context);
    }

    public SouthView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SouthView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

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

        int width = canvas.getWidth();
        mRadius = width / 2;
        mCirclrRadius = mRadius - 15;

        canvas.translate(width / 2, width / 2);//      

        mPaint = new Paint();
        mPaint.setColor(getResources().getColor(R.color.bg_black));//      
        mPaint.setStyle(Paint.Style.FILL);//    
        mPaint.setAntiAlias(true);//   
        canvas.drawCircle(0, 0, mRadius, mPaint);//        

        mPaint.setColor(Color.WHITE);
        mPaint.setStrokeWidth(5);
        mPaint.setStyle(Paint.Style.STROKE);

        RectF rectF = new RectF(-mCirclrRadius, -mCirclrRadius, mCirclrRadius, mCirclrRadius);
        for (int i = 0; i < 4; i++) {
            canvas.drawArc(rectF, 10, 70, false, mPaint);
            canvas.rotate(90);
        }

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_south);
        Matrix matrix = new Matrix();
        float f = (float) width / bitmap.getWidth();
        matrix.postScale(f, f);//       
        Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        canvas.rotate(mDegrees++);
        canvas.drawBitmap(dstbmp, -bitmap.getWidth() * f / 2, -bitmap.getWidth() * f / 2, mPaint);
        canvas.rotate(-mDegrees*5);

    }

    public void rotateBmp(){
        while (true){
            postInvalidate();//     UI
        }
    }
}

사용법

southView=(SouthView)view.findViewById(R.id.view_south);
new Thread(new Runnable() {
   @Override
   public void run() {
       southView.rotateBmp();
   }
}).start();

만약 네가 나의 풍격을 좋아한다면, 이 문장을 보면 canvas와paint가 롤러스 시계를 그릴 수 있다

좋은 웹페이지 즐겨찾기