android - Scale Bitmap maintaining aspect ratio and fitting both width and height -
i want scale bitmap maintaining aspect ratio, fitting required dimensions. this answer scales bitmap , maintains aspect ratio, leaves blank space unless image perfect square. need fill both width , height, fit_xy
scaletype property of imageview
.
based on streets of boston's answer, made method scales , returns bitmap desired width , height, fitting both dimensions (no blank space!). automatically adapts more horizontal or more vertical images.
public bitmap resizebitmapfitxy(int width, int height, bitmap bitmap){ bitmap background = bitmap.createbitmap(width, height, bitmap.config.argb_8888); float originalwidth = bitmap.getwidth(), originalheight = bitmap.getheight(); canvas canvas = new canvas(background); float scale, xtranslation = 0.0f, ytranslation = 0.0f; if (originalwidth > originalheight) { scale = height/originalheight; xtranslation = (width - originalwidth * scale)/2.0f; } else { scale = width / originalwidth; ytranslation = (height - originalheight * scale)/2.0f; } matrix transformation = new matrix(); transformation.posttranslate(xtranslation, ytranslation); transformation.prescale(scale, scale); paint paint = new paint(); paint.setfilterbitmap(true); canvas.drawbitmap(bitmap, transformation, paint); return background; }
Comments
Post a Comment