Matrix工具类是对图形进行特效处理。
Matrix 是一个矩阵工具类,本身不能对图形进行变换,可以与其他API来结合使用。
获取Matrix对象,可以直接创建,可以从其他封装了Matrix类中获取,Transformation里面就封装了Matrix对象。
调用Matrix对象的方法可以对图形图像进行平移,缩放,旋转,倾斜等。
需要将程序对Matrix所做的变换应用到指定图像或组件上面。
下面是一个Matrix使用方法的例子,利用按键来控制Bitmap的倾斜和缩放。
class MyView extends View {
/**源图*/
private Bitmap bitmap;
/**Matrix对象*/
private Matrix matrix = new Matrix();
/**倾斜度*/
public float ox = 0.0f;
/**缩放度*/
public float scale = 1.0f;
/**源图尺寸*/
private int width, height;
/**缩放还是倾斜*/
private boolean isScale = false;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
//得到位图
bitmap = ((BitmapDrawable) this.getResources().getDrawable(
R.drawable.ic_launcher)).getBitmap();
width = bitmap.getWidth();
height = bitmap.getHeight();
//按键控制,首先要获取到焦点
this.setFocusable(true);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//重置Matrix、倾斜状态时恢复到源图再进行缩放
matrix.reset();
if(isScale){
//x/y轴同比放大缩小
matrix.setScale(scale, scale);
}else{
matrix.setSkew(ox,ox);
}
//得到新图
Bitmap b = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
//将程序对Matrix所做的变换应用到指定图像或组件上面
canvas.drawBitmap(b, matrix, null);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT://倾斜
isScale=false;
ox+=0.1;
//刷新界面,view类也有该方法
postInvalidate();
break;
case KeyEvent.KEYCODE_DPAD_RIGHT://倾斜
isScale=false;
ox-=0.1;
postInvalidate();
break;
case KeyEvent.KEYCODE_DPAD_UP://放大
isScale=true;
if(scale<2.0){
scale+=0.1;
}
postInvalidate();
break;
case KeyEvent.KEYCODE_DPAD_DOWN://缩小
isScale=true;
if(scale>0.5){
scale-=0.1;
}
postInvalidate();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
原文:http://blog.csdn.net/u010152805/article/details/18992413