How to rotate an image in a Gallery view

妖精的绣舞 提交于 2019-12-09 22:01:11

问题


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 position, 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);

回答1:


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



来源:https://stackoverflow.com/questions/6050642/how-to-rotate-an-image-in-a-gallery-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!