1. 程式人生 > >一個小Demo瞭解,Cavan的座標旋轉平移

一個小Demo瞭解,Cavan的座標旋轉平移

package com.example.meitu.testdemo;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

/**

 */

public class TestVIew extends View {

    Paint paint;
    String text = "12345";
    Paint paint2;
    public TestVIew(Context context) {
        this(context, null);
    }

    public TestVIew(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TestVIew(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setTextSize(50);
        paint2 = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float y = getMeasuredHeight()/3*2;
        float x = getMeasuredWidth()/3;
        canvas.drawText(text,x,y,paint);
        Rect rect  = new Rect();
        paint.getTextBounds(text, 0, text.length(), rect);
        int width = rect.width();
        int height = rect.height();
        canvas.save();
        canvas.translate(x+width/2,y-height/2);
        paint2.setColor(Color.RED);
        canvas.drawRect(0,0,300,200,paint2);
        canvas.rotate(90,0,0);
        paint2.setColor(Color.BLUE);
        canvas.drawRect(0,0,300,200,paint2);
        canvas.drawText(text,-width/2,height/2,paint);
        canvas.restore();
        super.onDraw(canvas);
    }
}

需求很簡單,首先在在制定位置畫一段文字,然後,豎直的再畫一段數字

1.畫布的平移,將畫布平移到對應的中心點         canvas.translate(x+width/2,y-height/2);

2.畫布的旋轉,旋轉90度,然後進行繪畫

3.座標系恢復利用 save 和restore方法,恢復畫布的座標

4.注意點,這裡所謂的旋轉,平移和恢復其實都是座標系的平移旋轉和恢復,畫布只是一個相對的參照物