Skip to content

Instantly share code, notes, and snippets.

@tajchert
Created July 18, 2014 08:22
Show Gist options
  • Save tajchert/63eac65e6c8b9d2b7874 to your computer and use it in GitHub Desktop.
Save tajchert/63eac65e6c8b9d2b7874 to your computer and use it in GitHub Desktop.
Crop Top of a Bitmap to particular size.
//Author: Michal Tajchert
//tajchert.pl
public Bitmap scaleTopCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;
RectF targetRect = new RectF(0, 0, scaledWidth, scaledHeight);
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);
return dest;
}
@tajchert
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment