代碼實現:ide
1 public class MainActivity extends AppCompatActivity { 2
3 private ImageView img; 4
5 @Override 6 protected void onCreate(Bundle savedInstanceState) { 7 super.onCreate(savedInstanceState); 8 setContentView(R.layout.activity_main); 9 initView(); 10 //從資源文件中獲得圖片
11 Bitmap rawBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.abc); 12 // 獲得圖片原始的高寬
13 int rawHeight = rawBitmap.getHeight(); 14 int rawWidth = rawBitmap.getWidth(); 15 // 新創建矩陣
16 Matrix matrix = new Matrix(); 17 matrix.postScale(0.2f, 0.2f); 18
19 Bitmap newBitmap = Bitmap.createBitmap(rawBitmap, 0, 0, rawWidth, rawWidth, matrix, true); 20 BitmapDrawable bitmapDrawable=new BitmapDrawable(newBitmap); 21 img.setImageDrawable(bitmapDrawable); 22 } 23
24 private void initView() { 25 img = (ImageView) findViewById(R.id.img); 26 } 27 }