Skip to content

Instantly share code, notes, and snippets.

@Fullplate
Created August 13, 2014 07:20
Show Gist options
  • Save Fullplate/04509554ff11639ff2aa to your computer and use it in GitHub Desktop.
Save Fullplate/04509554ff11639ff2aa to your computer and use it in GitHub Desktop.
Android - Programmatic ImageView scaling
/**
* Create an ImageView with a set height and a scalable width that is scaled based on
* a provided image.
* Returns a null ImageView if image was not found.
*/
private ImageView getScaledImageView(String imagePath) {
int desiredHeightPx = 75;
ImageView iv = null;
File imageFile = new File(imagePath);
if (imageFile.exists()) {
// create new image view for logo
iv = new ImageView(getActivity());
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
// get width and height of image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imagePath, options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
// calculate vertical scaling required to fit image in heightwise
float scaleRequired = (desiredHeightPx * 1.0f) / imageHeight;
// calculate actual width and height of the final view, and create layoutparams for it
int actualWidth = (int) (imageWidth * scaleRequired);
int actualHeight = (int) (imageHeight * scaleRequired);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(actualWidth, actualHeight);
iv.setLayoutParams(lp);
// finally load image into view
iv.setImageURI(Uri.fromFile(new File(imagePath)));
}
else {
Logging.logger.warn("Creating image view but image file did not exist: "+imagePath);
}
return iv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment