在Android中,我定义了一个ImageView的layout_width为fill_parent(它占用了手机的全宽度)。
如果我放入ImageView的图像大于layout_width, Android会缩放?那么高度呢?当Android缩放图像时,它会保持纵横比吗?
我发现在ImageView的顶部和底部有一些空白当Android缩放一个比ImageView大的图像时。这是真的吗?如果是,我如何消除空白?
在Android中,我定义了一个ImageView的layout_width为fill_parent(它占用了手机的全宽度)。
如果我放入ImageView的图像大于layout_width, Android会缩放?那么高度呢?当Android缩放图像时,它会保持纵横比吗?
我发现在ImageView的顶部和底部有一些空白当Android缩放一个比ImageView大的图像时。这是真的吗?如果是,我如何消除空白?
当前回答
如果你想要一个ImageView在保持适当的纵横比的情况下,既能放大又能缩小,把这个添加到你的XML中:
android:adjustViewBounds="true"
android:scaleType="fitCenter"
在代码中添加:
// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);
我花了一段时间才让它工作,但这似乎在图像小于屏幕宽度和大于屏幕宽度的情况下都可以工作,而且它不会将图像框起来。
其他回答
看一下ImageView。ScaleType来控制和理解在ImageView中发生大小调整的方式。当图像被调整大小时(同时保持其纵横比),图像的高度或宽度可能会小于ImageView的维度。
以编程方式应用宽高比到Imageview:
aspectRatio = imageWidth/imageHeight
ratioOfWidth = imageWidth/maxWidth
ratioOfHeight = imageHeight/maxHeight
if(ratioOfWidth > ratioOfHeight){
imageWidth = maxWidth
imageHeight = imageWidth/aspectRatio
} else if(ratioOfHeight > ratioOfWidth){
imageHeight = maxHeight
imageWidth = imageHeight * aspectRatio
}
之后,您可以使用缩放位图图像视图
Bitmap scaledBitmap= Bitmap.createScaledBitmap(bitmap, (int) imageWidth , (int) imageHeight , true);
这是它在ConstraintLayout中为我工作的方式:
<ImageView
android:id="@+id/myImg"
android:layout_width="300dp"
android:layout_height="300dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"/>
然后在代码中,我设置drawable为:
ImageView imgView = findViewById(R.id.myImg);
imgView.setImageDrawable(ResourcesCompat.getDrawable(getResources(), R.drawable.image_to_show, null));
这很好地符合图像的长宽比,并保持它在中心。
你可以计算屏幕宽度。你可以缩放位图。
public static float getScreenWidth(Activity activity) {
Display display = activity.getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics();
display.getMetrics(outMetrics);
float pxWidth = outMetrics.widthPixels;
return pxWidth;
}
计算屏幕宽度和按屏幕宽度缩放的图像高度。
float screenWidth=getScreenWidth(act)
float newHeight = screenWidth;
if (bitmap.getWidth() != 0 && bitmap.getHeight() != 0) {
newHeight = (screenWidth * bitmap.getHeight()) / bitmap.getWidth();
}
之后就可以缩放位图了。
Bitmap scaledBitmap=Bitmap.createScaledBitmap(bitmap, (int) screenWidth, (int) newHeight, true);
如果你想要一个ImageView在保持适当的纵横比的情况下,既能放大又能缩小,把这个添加到你的XML中:
android:adjustViewBounds="true"
android:scaleType="fitCenter"
在代码中添加:
// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);
我花了一段时间才让它工作,但这似乎在图像小于屏幕宽度和大于屏幕宽度的情况下都可以工作,而且它不会将图像框起来。