Drawble高效创建缩略图方法

时间:2022-10-17 23:16:21


代码是从android源码代中抽出来的,感觉不错。。。如果大家有什么建议,一起交流,谢谢!!!




public Drawable createIconThumbnail(Drawable icon,int MIconWidth,int mIconHeight) {
int width = mIconWidth;
int height = mIconHeight;

final int iconWidth = icon.getIntrinsicWidth();
final int iconHeight = icon.getIntrinsicHeight();

if (icon instanceof PaintDrawable) {
PaintDrawable painter = (PaintDrawable) icon;
painter.setIntrinsicWidth(width);
painter.setIntrinsicHeight(height);
}

if (width > 0 && height > 0) {
if (width < iconWidth || height < iconHeight) {
final float ratio = (float) iconWidth / iconHeight;

if (iconWidth > iconHeight) {
height = (int) (width / ratio);
} else if (iconHeight > iconWidth) {
width = (int) (height * ratio);
}

final Bitmap.Config c = icon.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565;
final Bitmap thumb = Bitmap.createBitmap(mIconWidth,
mIconHeight, c);
final Canvas canvas = mCanvas;
canvas.setBitmap(thumb);
// Copy the old bounds to restore them later
// If we were to do oldBounds = icon.getBounds(),
// the call to setBounds() that follows would
// change the same instance and we would lose the
// old bounds
mOldBounds.set(icon.getBounds());
final int x = (mIconWidth - width) / 2;
final int y = (mIconHeight - height) / 2;
icon.setBounds(x, y, x + width, y + height);
icon.draw(canvas);
icon.setBounds(mOldBounds);
icon = new BitmapDrawable(getResources(), thumb);
} else if (iconWidth < width && iconHeight < height) {
final Bitmap.Config c = Bitmap.Config.ARGB_8888;
final Bitmap thumb = Bitmap.createBitmap(mIconWidth,
mIconHeight, c);
final Canvas canvas = mCanvas;
canvas.setBitmap(thumb);
mOldBounds.set(icon.getBounds());
final int x = (width - iconWidth) / 2;
final int y = (height - iconHeight) / 2;
icon.setBounds(x, y, x + iconWidth, y + iconHeight);
icon.draw(canvas);
icon.setBounds(mOldBounds);
icon = new BitmapDrawable(getResources(), thumb);
}
}

return icon;
}