转载请注明转自:noyet12的博客
博客原址:http://blog.csdn.net/u012975705/article/details/49992947
Canvas 即“画布”的意思,在Android中用其来进行2D绘画。
在使用canvas来进行绘图时,一般都会自定义一个View来重写它的onDraw方法:
public class CustomCanvas extends View {
public CustomCanvas(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
既然是绘图,自然就少不了画笔:Paint,canvas通过借用paint来绘制图像。
canvas中,有rotate、scale、translate等方法即旋转、缩放、平移,对于这几个方法必须注意:操作对想象是画布,发生旋转、缩放、平移的是画布,并且使用canvas绘制时其中的坐标参数是相对于画布的而不是相对于屏幕本身。单通过语言可能不太好理解,下面给出实例。
CanvasDemo:
第一步 自定义View并重写onDraw方法
package com.noyet.practice.canvasdemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.View;
/**
* package: com.noyet.practice.canvasdemo
* Created by noyet on 2015/11/23.
*/
public class CustomCanvas extends View {
private Paint mPaint;
private RectF mRect;
public CustomCanvas(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mRect = new RectF(100, 100, 150, 150);
canvas.drawRect(mRect, mPaint);
// canvas.save();
canvas.scale(2f, 2f);
canvas.rotate(10, 100, 100);
mPaint.setColor(Color.GRAY);
canvas.drawRect(mRect, mPaint);
// canvas.restore();
}
}
第二步 在屏幕中显示出来
package com.noyet.practice.canvasdemo;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CustomCanvas(this));
}
}
绘制结果:
从图中可以看到,当调用canvas.scale(2f, 2f)方法和,连坐标的时间权重都是原来的2倍了
时间: 2024-10-13 15:22:14