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.注意点,这里所谓的旋转,平移和恢复其实都是坐标系的平移旋转和恢复,画布只是一个相对的参照物