Home > Development > Keep Android ImageView in a Constant 4:3 Aspect Ratio

Keep Android ImageView in a Constant 4:3 Aspect Ratio

Recently I had a specification for showing thumbnail images in a constant 4:3 aspect ratio regardless of the aspect ratio of whatever image would be displayed. I found a lot of references to manipulating and scaling the image, but not many for scaling the ImageView itself. I did find one good clue from Bob Lee in this Stackoverflow post, so I adapted it.

In a subclass of ImageView you can override onMeasure(), as below, to force a 4:3 or other aspect ratio on the instances. If you are making thumbnails, you’ll also want to scale the bitmaps so they “fit” per your specifications. The specs from my UI designer were pretty specialized so I won’t include the code I used for scaling.

@Override protected void onMeasure(int widthMeasureSpec,
   int heightMeasureSpec) {
//   let the default measuring occur, then force the desired aspect ratio 
//   on the view (not the drawable).
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getMeasuredWidth();
//force a 4:3 aspect ratio   		   
int height = Math.round(width * .75f);
setMeasuredDimension(width, height);
}
About these ads
Categories: Development Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: