Android利用Matrix简单处理图片
16lz
2021-01-23
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
更多相关文章
- TextView中的文字添加阴影效果及Style的使用
- :Android实现程序前后台切换效果
- android带有文字的图片按钮的两种实现方式
- Android Kotlin TextView跑马灯效果
- android api Demo之自定义Animation,实现3D旋转效果
- Android 基于google Zxing实现二维码、条形码扫描,仿微信二维码扫
- Android Animation动画 控制动画的执行效果,速度等
- 演化理解 Android 异步加载图片