Matrix
在Android中,对图片的处理需要使用到Matrix类,Matrix是一个3 x 3的矩阵
图片的处理分为四个基本类型:
- Translate 平移变换
- Scale 缩放变换
- Rotate 旋转变换
- Skew 错切变换
图片变换的三种操作方式
- set(用于设置Matrix中的值)
- post(后乘,根据矩阵的原理,相当于左乘)
- pre(先乘,相当于矩阵中的右乘)
默认时,这四种变换都是围绕(0,0)点变换的,当然可以自定义围绕的中心点,通常围绕中心点。
通过将变换矩阵与原始矩阵相乘来达到变换的目的
- 平移(x’=x+tx;y’=y+ty)
- 缩放(x’=sx*x;y’=sy*y)
- 旋转(x’=cosβ*x-sinβ*y;y’=sinβ*x+cosβ*y)
例子
public class DrawView extends View{
Bitmap newBitmap;
Paint paint;
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
paint = new Paint();
newBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon_guster_header);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setAntiAlias(true);
paint.setColor(Color.WHITE);
paint.setTextSize(14);
// 绘制原图 图中1
canvas.drawBitmap(newBitmap, 10, 10, paint);
canvas.restore();
canvas.save();
// 绘制平移旋转缩放组合 图中2
Matrix m1 = new Matrix();
m1.setTranslate(800, 600);
Matrix m2 = new Matrix();
m2.setRotate(40);
Matrix m3 = new Matrix();
m3.setConcat(m1, m2);
m1.setScale(0.8f, 0.8f);
m2.setConcat(m3, m1);
canvas.drawBitmap(newBitmap, m2, paint);
canvas.restore();
canvas.save();
// 绘制平移、缩放、透明度组合 图中3
paint.setAlpha(180);
m1.setTranslate(500, 200);
m2.setScale(1.3f, 1.3f);
m3.setConcat(m1, m2);
canvas.drawBitmap(newBitmap, m3, paint);
canvas.restore();
canvas.save();
// 重置画笔,取消透明度
paint.reset();
// 绘制负向缩放 使用postTranslate 将图片移动 图中4
Matrix m4 = new Matrix();
m4.setScale(1 , -1);
m4.postTranslate(10, 10 + newBitmap.getHeight() * 2);
canvas.drawBitmap(newBitmap, m4, paint);
canvas.restore();
canvas.save();
paint.reset();
// paint.setTextSize(40);
// paint.setColor(0xFF333333);
// canvas.drawText("abcfewfewfwefewfewfwefewfe", 20, 200, paint);
// paint.reset();
}
}
- 效果图