我试图将一个位图绘制到画布上。它导致拉伸位图。我想要的是如果图像较小则不拉伸,如果图像大于显示器则裁剪图像。如何实现这一目标。
我有一个自定义drawable,扩展了DrawableWrapper
public class MyDrawable extends DrawableWrapper {
public MyDrawable(Drawable drawable) {
super(drawable);
}
public MyDrawable(final Context context, Bitmap bitmap) {
this(new BitmapDrawable(context.getResources(),bitmap));
}
我在boundsChnage()
中使用此代码 protected void onBoundsChange(Rect bounds) {
mBitmap = Bitmap.createBitmap(bounds.width(), bounds.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmap);
super.draw(canvas);
}
这导致拉伸拉伸的可拉伸部分的裁剪部分。
答案 0 :(得分:0)
i think it will help you.
Bitmap scaleBitmap = scaleBitmap(bitmap);
RectF rectF = new RectF(0, (mHeight scaleBitmap.getHeight()),
scaleBitmap.getWidth(), scaleBitmap.getHeight());
canvas.drawBitmap(scaleBitmap, null, rectF, null);
private Bitmap scaleBitmap(Bitmap bm) {
int width = bm.getWidth();
int height = bm.getHeight();
Log.v("Pictures", "Width and height are " + width + "--" + height);
int mWidth = this.getResources().getDisplayMetrics().widthPixels;
int mHeight = this.getResources().getDisplayMetrics().heightPixels;
if (width > height) {
// landscape
int ratio = width / mWidth;
width = mWidth;
height = height / ratio;
} else if (height > width) {
// portrait
int ratio = height / mHeight;
height = mHeight;
width = width / ratio;
} else {
// square
height = mWidth;
width = mWidth;
}
Log.v("Pictures", "after scaling Width and height are " + width + "--" + height);
bm = Bitmap.createScaledBitmap(bm, width, height, true);
return bm;
}