package com.mz.demo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Path.Direction;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class MysurfaceView extends SurfaceView implements Callback {
private Paint paint;
private Canvas canvas;
private SurfaceHolder sfh;
private Bitmap bmp;
private Bitmap bmp1;
public MysurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
paint=new Paint();//实例化画笔
paint.setAntiAlias(true);
sfh=this.getHolder();//实例化
sfh.addCallback(this);//监听
bmp=BitmapFactory.decodeResource(getResources(), R.drawable.role_right1);
bmp1=BitmapFactory.decodeResource(getResources(), R.drawable.background);
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
myDraw();
}
private void myDraw() {
// TODO Auto-generated method stub
canvas=sfh.lockCanvas();//实例化画布 并且锁定画布
canvas.drawColor(Color.WHITE);//设置背景白色
// canvas.drawBitmap(bmp, 0, 0, paint);
//旋转图像的特效 I.利用矩阵旋转(针对图像进行调整)
//1.实例化一个矩阵对象
// Matrix mt=new Matrix();
// Matrix mt2=new Matrix();
//2.图像按照指定的角度进行旋转
//mt.setRotate(30);旋转30度
//canvas.drawBitmap(bmp, mt, paint);
//mt.setRotate(30, 100, 100);
//mt.postRotate(30);
//mt.postRotate(30, bmp.getWidth()/2, bmp.getHeight()/2);//以图像中心旋转
//mt.setScale(2f, 2f);//放大
//mt.setScale(2f, 2f, bmp.getWidth()/2, bmp.getHeight()/2);//以图片中心放大
//mt.setScale(0.5f, 0.5f);
//mt.setScale(-1, 1, bmp.getWidth()/2, bmp.getHeight()/2);//以y轴对称 *考试
// mt.setScale(1, -1, bmp.getWidth()/2, bmp.getHeight()/2);//以x轴对称 *考试
// mt2.setScale(-1, 1, bmp.getWidth()/2, bmp.getHeight()/2);//以y轴对称 *考试
// mt.setTranslate(100, 100);//平移
// canvas.drawBitmap(bmp, mt, paint);
// canvas.drawBitmap(bmp, mt2, paint);
//II.使用画布添加图像的特效
// canvas.save();//在画布添加特效之前,需要将正常的状态进行保存
// canvas.rotate(30);//旋转30度
// canvas.drawBitmap(bmp, 100, 100, paint);
// canvas.restore();//把画布恢复旋转之前的状态
// canvas.drawBitmap(bmp, 200, 100, paint);
//canvas.drawBitmap(bmp1, 0, 0, paint);
canvas.save();//保存当前画布
canvas.clipRect(0, 0, 100, 100);//显示大小
canvas.drawBitmap(bmp1, 0, 0, paint);
canvas.restore();
Path path=new Path();
path.addCircle(100, 100, 60, Direction.CCW);
canvas.clipPath(path);
canvas.drawBitmap(bmp1, 0, 0,paint);
sfh.unlockCanvasAndPost(canvas);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
由于代码之间会互相影响
所以注释了。
在使用画布实现图像特效时要熟练使用save()方法 和restore()方法