核心代码:
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView iv;
private ImageView iv_after;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) this.findViewById(R.id.iv);
iv_after = (ImageView) this.findViewById(R.id.iv_after);
}
/**
* 缩放图片
* @param view
*/
public void scalePic(View view) {
// 从图库中选择一张图片
Intent intent = new Intent();
intent.setAction("android.intent.action.PICK");
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
this.startActivityForResult(intent, 0);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
//获取要查看的图片的路径
try {
Uri uri = data.getData();
iv.setImageURI(uri);
//得到原图的bitmap 只读
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
//空白可可以修改的bitmap
Bitmap alterBitmap = Bitmap.createBitmap(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getConfig());
//创建画布
Canvas canvas = new Canvas(alterBitmap);
//创建画笔
Paint paint = new Paint();
paint.setColor(Color.BLACK);
Matrix matrix = new Matrix();
// matrix.setValues(new float[] {
// 0.5f, 0, 0,
// 0, 0.5f, 0,
// 0, 0, 1
// });
matrix.setScale(0.5f, 0.5f);
canvas.drawBitmap(bitmap, matrix, paint);
iv_after.setImageBitmap(alterBitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|