开发者

Android: Resizing and scaling a part of the image

Given an image, I want to be able to scale only a part of that image. Say, I want to expand half of the image so that, that half takes up the whole space.

How is this possible?

Will ImageView fitXY work because I thought it'll work only for the whole original image.

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout linearLayout = new LinearLayout(this); 

           Bitmap bitmap = BitmapFactory.decodeResource(getResources(),       R.drawable.icon);   


            int width = bitmap.getWidth();   

             int height = bitmap.getHeight();   

            int newWidth = 640;   

            int newHeight = 480;   


             float scaleWidth = ((float) newWidth) / width;   

            float scaleHeight = ((float) newHeight) / height;   


            Matrix matrix = new Matrix();   

            matrix.postScale(scaleWidth, scaleHeight);   

             开发者_Python百科// create the new Bitmap object   

             Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 50, 50, width,   

                     height, matrix, true);   

             BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);   



             ImageView imageView = new ImageView(this);   

             imageView.setImageDrawable(bmd);   

             imageView.setScaleType(ScaleType.CENTER);   



             linearLayout.addView(imageView, new LinearLayout.LayoutParams(   

                     LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));   

             setContentView(linearLayout);   
  } 
} 

This works only if in createBitmap, the X and Y coordinates of the first pixels in the source are 0. meaning, I'm not able to take a subset of the image. Only able to scale the whole image. But createBitmap is meant to subset an image.

In the log, when the parameters are not 0, I get the following exception: java.lang.IllegalArgumentException: x + width must be <= bitmap.width()

Please help


First you have to create a new bitmap with the part you want to scale using

createBitmap() //pass the source bitmap, req height and width

Now from the result bitmap, you have to create your scaled bitmap using

createScaledbitmap() //pass the result bitmap , req width, height

For exapmle:

Bitmap originalBitmap = BitmapFactory.decodeResource(res, id);
Bitmap partImage = originalBitmap.createBitmap(width, height, config);
Bitmap scaledImage = partImage.createScaledBitmap(partImage, dstWidth, dstHeight, filter);


So I had to fix a couple of Typos, but this example did a good job for me.http://www.anddev.org/resize_and_rotate_image_-_example-t621.html typos:

int width = bitmapOrg.width();
int height = bitmapOrg.height();

become:

int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();

otherwise, worked when I tried it agains SDK 7

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜