android开发笔记之多媒体—图像的操作

1.拿到原图

baseBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_small_1);

2.先拿到一张与原图一样大小的纸,内容空白

copyBitmap = Bitmap.createBitmap(baseBitmap.getWidth(), baseBitmap.getHeight(), baseBitmap.getConfig());

3.将这张纸固定在画板上

canvas = new Canvas(copyBitmap);

4.找一根画笔

paint = new Paint();

5.按照一定规则处理图片

Matrix matrix = new Matrix();//1:1

6.将处理过的图片画出来,照着原图画

canvas.drawBitmap(baseBitmap, matrix, paint);

7.将画好的图片的显示在ImageView组件上

iv.setImageBitmap(copyBitmap);

核心代码:

public class MainActivity extends Activity {

    private ImageView iv;
    //画纸
    private Bitmap baseBitmap;  //原图
    private Bitmap copyBitmap;  
    //画布
    private Canvas canvas;
    //画笔
    private Paint paint;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
    }
    //处理图像
    public void operation(View view) {
        //1拿到原图
        baseBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.img_small_1);
        //2.先拿到一张与原图一样大小的纸,内容空白
        copyBitmap = Bitmap.createBitmap(baseBitmap.getWidth(), baseBitmap.getHeight(), baseBitmap.getConfig());
        //3.将这张纸固定在画板上
        canvas = new Canvas(copyBitmap);
        //4.找一根画笔
        paint = new Paint();
        paint.setAlpha(200);
        //5.按照一定规则处理图片
        Matrix matrix = new Matrix();//1:1
        //缩放
// matrix.setScale(0.5f, 0.5f); //1:2即1/2
        //位移
// matrix.setTranslate(50f, 50f);
        //旋转
// matrix.setRotate(45f); //顺时针45度旋转,默认以图片左上角为原点
// matrix.setRotate(45, baseBitmap.getWidth()/2, baseBitmap.getHeight()/2); //顺时针45度旋转,沿中心点旋转
        //镜面 
// matrix.setScale(-1f, 1f);//翻面
// matrix.postTranslate(baseBitmap.getWidth(), 0); //如果要对图片进行多次操作,则用postxxx();
        //倒影
        matrix.setScale(1f, -1f);
        matrix.postTranslate(0, baseBitmap.getHeight());
        //6.将处理过的图片画出来,照着原图画
        canvas.drawBitmap(baseBitmap, matrix, paint);
        iv.setImageBitmap(copyBitmap);
    }
}

结果:

你可能感兴趣的:(Android开发,多媒体)