我使用图像视图来显示客户的图片,并使用此命令在图像视图中缩放我的图像
iv.setScaleType(ImageView.ScaleType.CENTER_CROP);
但是在这个命令之后,客户的头部被部分切割了,所以我想在中心裁剪命令之后将图像缩放到按钮,这样图像的底部就会被切割
没有开箱即用的解决方案可以满足您的要求。您需要自己进行缩放。这是你如何做到的:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// we need to wait till the layout has been inflated to get the size of the ImageView
final ImageView iv = (ImageView) findViewById(R.id.image);
iv.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
scaleBitmap(iv);
}
}
);
}
private void scaleBitmap(ImageView iv) {
// get ImageView and determine width & height
int imageWidth = iv.getWidth();
int imageHeight = iv.getHeight();
Rect imageRect = new Rect(0, 0, imageWidth, imageHeight);
// determine destination rectangle
BitmapDrawable drawable = (BitmapDrawable)iv.getDrawable();
Bitmap sourceBitmap = drawable.getBitmap();
Rect bitmapRect = new Rect(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
// determine source rectangle
Rect sourceRect = computeSourceRect(imageRect, bitmapRect);
// here's where we do the magic
Bitmap scaledBitmap = Bitmap.createBitmap(imageRect.width(), imageRect.height(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.drawBitmap(sourceBitmap, sourceRect, imageRect, new Paint());
iv.setImageBitmap(scaledBitmap);
}
private Rect computeSourceRect(Rect imageRect, Rect bitmapRect) {
float imageWidth = (float) imageRect.width();
float imageHeight = (float) imageRect.height();
float bitmapWidth = (float) bitmapRect.width();
float bitmapHeight = (float) bitmapRect.height();
float aspectRatioImage = imageWidth / imageHeight;
float aspectRatioBitmap = bitmapWidth / bitmapHeight;
if (aspectRatioImage<aspectRatioBitmap) {
float newWidth = bitmapHeight * aspectRatioImage;
float widthOffset = (bitmapWidth - newWidth) / 2f;
return new Rect((int) widthOffset, 0, (int) (widthOffset + newWidth), (int) bitmapHeight);
}
else {
float newHeight = bitmapWidth / aspectRatioImage;
float heightOffset = (bitmapHeight - newHeight) / 2f;
// return this for center_crop
//return new Rect(0, (int) heightOffset, (int) bitmapWidth, (int) (heightOffset + newHeight));
// return this for bottom align
return new Rect(0, 0, (int) bitmapWidth, (int) newHeight);
}
}
这基本上根据您的要求将位图缩放为 ImageView(可以很容易地修改为使用按钮)。您可以通过这种方式进行任何可能的缩放。