Java tutorial
//package com.java2s; //License from project: Open Source License import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; public class Main { public static Bitmap cropMaxVisibleBitmap(Drawable drawable, int iconSize) { Bitmap tmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(tmp); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); Rect crop = new Rect(tmp.getWidth(), tmp.getHeight(), -1, -1); for (int y = 0; y < tmp.getHeight(); y++) { for (int x = 0; x < tmp.getWidth(); x++) { int alpha = (tmp.getPixel(x, y) >> 24) & 255; if (alpha > 0) { // pixel is not 100% transparent if (x < crop.left) crop.left = x; if (x > crop.right) crop.right = x; if (y < crop.top) crop.top = y; if (y > crop.bottom) crop.bottom = y; } } } if (crop.width() <= 0 || crop.height() <= 0) { return Bitmap.createScaledBitmap(tmp, iconSize, iconSize, true); } // We want to crop a square region. float size = Math.max(crop.width(), crop.height()); float xShift = (size - crop.width()) * 0.5f; crop.left -= Math.floor(xShift); crop.right += Math.ceil(xShift); float yShift = (size - crop.height()) * 0.5f; crop.top -= Math.floor(yShift); crop.bottom += Math.ceil(yShift); Bitmap finalImage = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888); canvas.setBitmap(finalImage); float scale = iconSize / size; canvas.scale(scale, scale); canvas.drawBitmap(tmp, -crop.left, -crop.top, new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG)); canvas.setBitmap(null); return finalImage; } }