Android中Canvas和Paint简单例子
package com.canvas.paint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class mainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
class MyView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Canvas canvas;
public MyView(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);//设置Surface生命周期回调
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
canvas = mHolder.lockCanvas();//获得画布
canvas.drawColor(Color.WHITE);//设置画布背景为白色
Paint mPaint = new Paint();
//画矩形
mPaint.setColor(Color.YELLOW);
canvas.drawRect(100, 200, 200, 300, mPaint);
canvas.save();//每画完一个图做备忘存储,以保证与其它图形互不影响
//画旋转
canvas.rotate(45);//旋转角度45度
mPaint.setColor(Color.GREEN);
canvas.drawRect(150, 10, 200, 60, mPaint);//画矩形
canvas.save();
//画渐变色圆形
Shader mShader=new LinearGradient(0,0,100,100,
new int[]{Color.RED,Color.GREEN,Color.BLUE,Color.YELLOW},
null,Shader.TileMode.REPEAT);//使用着色器
mPaint.setShader(mShader);
canvas.drawCircle(500, 150, 80, mPaint);
/*
canvas.save();
//画三角形
mPaint.setStyle(Paint.Style.STROKE);//设置空心
mPaint.setStrokeWidth(3);//设置p外框宽度
Path path=new Path();
path.moveTo(10,330);
path.lineTo(70,330);
path.lineTo(40,270);
path.close();
canvas.drawPath(path,mPaint);
canvas.save();
// 画梯形
mPaint.setAntiAlias(true);//去掉边缘锯齿
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.FILL);//设置实心
Path path1=new Path();
path1.moveTo(10,410);
path1.lineTo(70,410);
path1.lineTo(55,350);
path1.lineTo(25,350);
path1.close();
canvas.drawPath(path1,mPaint);
canvas.save();
//画椭圆形
mPaint.setAntiAlias(true);//去掉边缘锯齿
mPaint.setColor(Color.RED);
RectF re=new RectF(10,220,70,250);
canvas.drawOval(re,mPaint);
*/
canvas.restore();
mHolder.unlockCanvasAndPost(canvas);//完成绘图后解锁递交画布视图
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
}