要想处理图像,必须经过以下步骤:
1.拿到原图
2.拿到一张与原图相同的纸
3.然后将这张纸固定在画板上
4.找一根画笔
5.按照一定规则处理原图图片
6.将处理过的图片用画笔画出来
代码编写:
布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="操作图片"
android:onClick="btn"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv1"
android:src="@drawable/img_small_1"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv2"
android:background="#000000"/>
</LinearLayout>
activity:
public class MainActivity extends Activity {
private ImageView iv2;
//原图
private Bitmap baseBitmap;
//画纸
private Bitmap copyBitmap;
//画板
private Canvas canvas;
//画笔
private Paint paint;
public void btn(View view) {
// TODO Auto-generated method stub
//拿到原图
baseBitmap=BitmapFactory.decodeResource(getResources(), R.drawable.img_small_1);
//1.先拿到一张与原图相同的纸
copyBitmap=Bitmap.createBitmap(baseBitmap.getWidth(), baseBitmap.getHeight(), baseBitmap.getConfig());
//2.然后将这张纸固定在画板上
canvas=new Canvas(copyBitmap);
//3.找一根画笔
paint=new Paint();
//4.按照一定规则处理原图图片
Matrix matrix=new Matrix();//1:1
//缩放
//matrix.setScale(0.5f, 0.5f);
//位移
//matrix.setTranslate(50f, 50f);
//旋转
//matrix.setRotate(45);//顺时针旋转45度,默认以左上角为原点
//matrix.setRotate(45, baseBitmap.getWidth()/2, baseBitmap.getHeight()/2);//沿中心点旋转
//镜面效果
matrix.setScale(-1f, 1f);
//matrix.setTranslate(baseBitmap.getWidth(),0);
matrix.postTranslate(baseBitmap.getWidth(), 0);//如果要对图片进行多次操作,要用postTranslate
//倒影
matrix.setScale(1f, -1f);
matrix.postTranslate(0, baseBitmap.getHeight());
//5.将处理过的图片用画笔画出来
canvas.drawBitmap(baseBitmap, matrix, paint);
iv2.setImageBitmap(copyBitmap);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv2=(ImageView) findViewById(R.id.iv2);
}
}
效果图: