Android利用Matrix简单处理图片

Android图片变换详解

Matrix是由一个3×3的矩阵组成的,因为涉及到数学中的矩阵概念先不做解释。Matrix已经给我们封装好了一些方法,这里先看看每个方法的效果。

程序目录如下:

main.xml展示变换前后的图片:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<imageview 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
       android:src="@drawable/picture1" 
    /> 
    <textview android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="下图是改变后的效果" /> 
<imageview android:id="@+id/myimage" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
       android:src="@drawable/picture1" 
    />

MainActivity负责利用Matrix处理图片,首先演示图片旋转效果,主要代码:

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    
    ImageView imageView; 
    Matrix mMatrix = new Matrix(); 
    imageView = (ImageView) findViewById(R.id.myimage);
    Bitmap bmp = ((BitmapDrawable) getResources().getDrawable( 
            R.drawable.picture1)).getBitmap();
   mMatrix.setRotate(60);
    Bitmap bm = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), 
            bmp.getHeight(), mMatrix, true);
    imageView.setImageBitmap(bm); 
}

注意:Matrix的操作,总共分为translate(平移),rotate(旋转),scale(缩放)和skew(倾斜)四种,每一种变换在
Android的API里都提供了set, post和pre三种操作方式,除了translate,其他三种操作都可以指定中心点。
set是直接设置Matrix的值,每次set一次,整个Matrix的数组都会变掉。
post是后乘,当前的矩阵乘以参数给出的矩阵。可以连续多次使用post,来完成所需的整个变换。
例如,要将一个图片旋转30度,然后平移到(100,100)的地方,那么可以这样做:

Matrix m = new Matrix();  
m.postRotate(30);  
m.postTranslate(100, 100);

将图片旋转60度:

图片倾斜:mMatrix.postSkew(0.3f, 0.7f);效果:

图片缩放,x轴缩小0.5倍,y轴扩大2.5倍:mMatrix.setScale(0.5f, 2.5f);效果:

 附件: http://www.oschina.net/code/snippet_157182_8945

 

转载于:https://my.oschina.net/liux/blog/41881

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值