Matrix 简介

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();  
    }
}
  • 效果图
    这里写图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值