Android绘制进阶之三:在位图上(Bitmap)绘制位图(Bitmap)
3604 点击·0 回帖
![]() | ![]() | |
![]() | 1,点击按钮,指定action和uri,设定结果码(ResultCode).到达手机默认相册的Gallery. ![]() 代码如下: 1. public void onClick(View v) { 2. // TODO Auto-generated method stub 3. Intent intent = new Intent(Intent.ACTION_PICK, 4. Android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//启动照片Gallery 5. startActivityForResult(intent, 0); 6. } 2,选择图片,返回所选照片uri信息 代码如下: 1. @Override 2. protected void onActivityResult(int requestCode, int resultCode, Intent intent) { 3. // TODO Auto-generated method stub 4. super.onActivityResult(requestCode, resultCode, intent); 5. 6. if (resultCode == RESULT_OK) {//操作成功 7. Uri imgFileUri = intent.getData();//获得所选照片的信息 3,处理图片,设定合适的尺寸(正好适应屏幕) 设定BitmapFactory.Options 参数inJustDecodeBounds = true,即不创建bitmap,但可获取bitmap的相关属性。以宽高比例差距 最大者为基准。 代码如下: 1. //由于返回的图像可能太大而无法完全加载到内存中。系统有限制,需要处理。 2. Display currentDisplay = getWindowManager().getDefaultDisplay(); 3. int defaultHeight = currentDisplay.getHeight(); 4. int defaultWidth = currentDisplay.getWidth(); 5. 6. BitmapFactory.Options bitmapFactoryOptions = new BitmapFactory.Options(); 7. bitmapFactoryOptions.inJustDecodeBounds = true;///只是为获取原始图片的尺寸,而不返回Bitmap对象 8. //注上:If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, 9. //allowing the caller to query the bitmap without having to allocate the memory for its pixels 10. try { 11. Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgFileUri), null, bitmapFactoryOptions); 12. int outHeight = bitmapFactoryOptions.outHeight; 13. int outWidth = bitmapFactoryOptions.outWidth; 14. int heightRatio = (int) Math.ceil((float)outHeight/defaultHeight); 15. int widthRatio = (int) Math.ceil((float)outWidth/defaultWidth); 16. 17. if (heightRatio > 1 || widthRatio >1) { 18. if (heightRatio > widthRatio) { 19. bitmapFactoryOptions.inSampleSize = heightRatio; 20. } else { 21. bitmapFactoryOptions.inSampleSize = widthRatio; 22. } 23. } 4,inJustDecodeBounds = false,创建将此bitmap赋给第一个ImageView。 代码如下: 1. bitmapFactoryOptions.inJustDecodeBounds = false; 2. bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imgFileUri), null, bitmapFactoryOptions); 3. 4. mImageShow.setImageBitmap(bitmap); 5,绘制bitmap(选中的图片),赋给第二个ImageView 代码如下: 1. /* 2. * 在位图上绘制位图 3. */ 4. 5. Bitmap bitmapAltered = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), bitmap.getConfig()); 6. 7. Canvas canvas = new Canvas(bitmapAltered);//bitmap提供了画布,只在此提供了大小尺寸,偏移后并未有背景显示出来 8. 9. 10. Paint paint = new Paint(); 11. 12. canvas.drawBitmap(bitmap, 0, 0, paint);//绘制的图片和之前的一模一样 13. 14. mImageAltered.setImageBitmap(bitmapAltered); | |
![]() | ![]() |