开发者

How to rotate an image in a Gallery view

开发者 https://www.devze.com 2023-03-06 17:00 出处:网络
This is a simple problem, but I wonder if it has a non-expensive solution. I have a gallery view which loads images from memory, either SD card or resources. Their size is 480x800, so the code sample

This is a simple problem, but I wonder if it has a non-expensive solution.

I have a gallery view which loads images from memory, either SD card or resources. Their size is 480x800, so the code samples them down and show as thumbnails in a Gallery View. All works fine, kind of...

Some images are landscape while some portrait. The gallery’s imageview layout shows them all as landscape thus all portrait images look badly stretched!

Since these images are abstract drawings I would like to rotate the portrait ones so that they all nicely and evenly fit in the gallery. I could detect their orientation by comparing their width and height and then rotate the portrait ones using Matrix and canvas, but that may be too expensive and slow to run in getView() of a BaseAdapter.

Can anybody think of a less expensive way to do it?

    public View getView(int positio开发者_运维百科n, View convertView, ViewGroup parent){   
        ImageView i = new ImageView(mContext);   
        Bitmap bm = null;

        if (mUrls[position] != null){
            bm = BitmapFactory.decodeFile(mUrls[position].toString(),options); 
            if (bm != null){
                //here could use a bitmap rotation code
                //....
                i.setImageBitmap(bm);
            }
        }else{
            bm = BitmapFactory.decodeResource(getResources(), R.drawable.deleted);
            i.setImageBitmap(bm);
        }
        i.setScaleType(ImageView.ScaleType.FIT_XY);   
        i.setLayoutParams(new Gallery.LayoutParams(200, 130)); 
        i.setBackgroundResource(mGalleryItemBackground);
        return i;   
    }

EDIT

After some testing I am using the code below to rotate the image which is not super-fast but it can do at the moment.

int w = bm.getWidth();
int h = bm.getHeight();
if (w < h){
  Matrix matrix = new Matrix(); 
  matrix.postRotate(-90);
  bm = Bitmap.createBitmap(bm, 0, 0, w, h, matrix, false);    
}
i.setImageBitmap(bm);


Enter the Matrix!!!

Resize and Rotate Image - Example

very useful for me, hope it helps

  if (bm != null){
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);   
        BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
        i.setImageBitmap(bmd); 
       }

recycling works, i recommend use asynctask to load the images this avoid the UI blocks.

Heres an example::

http://android-apps-blog.blogspot.com/2011/04/how-to-use-asynctask-to-load-images-on.html

another example::

http://open-pim.com/tmp/LazyList.zip

0

精彩评论

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