Gra*_*eme 18 android imageview android-layout
我有一个比我想要的容器更小的图像.我希望图像能够拉伸,保持其纵横比,使其达到最大可能尺寸.
为了说明这个问题:
<ImageView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/thumbnail"
android:scaleType="fitXY"
android:adjustViewBounds="true"/>
Run Code Online (Sandbox Code Playgroud)
在ImageView上述将被拉伸以填充所述容器的宽度.的@drawable含有还沿x轴拉伸它,以适应宽度的ImageView这是完美的.然而问题是标记的尺寸wrap_content(在这种情况下是高度)保持与@drawables初始高度相同的尺寸.
我在这里阅读了有关ScaleType的文档,但在那里找不到答案.
下图描述了上面的代码:

Current behaviour Desired Behaviour
Run Code Online (Sandbox Code Playgroud)
编辑
一个ImageViewGIVEN scaleType="fitCenter"将准确地扩大/收缩@drawable在它的内部,同时保持它的高宽比生长尽可能大.
在ImageView之前的S尺寸被定义@drawable为以任何方式进行缩放.在ImageView中它包含尺寸标注不结垢影响@drawable.
XML
XML中唯一的解决方案是使用"match_parent"或使用离散的最大值,而不是"wrap_content"尽可能使用.这将确保ImageView正确的尺寸,这意味着添加scaleType="fitCenter"将确保@drawable然后正确缩放.
编程方式
这很难看,但是你可以在给出尺寸给出离散值之后调整ImageView的大小:
final ImageView thumbnailView = (ImageView) toReturn.findViewById(R.id.thumbnail);
ViewTreeObserver thumbnailViewVto = thumbnailView.getViewTreeObserver();
thumbnailViewVto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
private boolean changed = false;
@Override
public void onGlobalLayout() {
if(!changed) {
Drawable image = getResources().getDrawable(R.drawable.thumbnail);
float heighToWidthRatio = image.getIntrinsicWidth()/image.getIntrinsicHeight();
int height = thumbnailView.getHeight();
thumbnailView.setLayoutParams(
new LayoutParams(
(int) (height * heighToWidthRatio), height));
changed = true;
}
}
});
Run Code Online (Sandbox Code Playgroud)
编辑
final ImageView thumbnailView = (ImageView) toReturn.findViewById(R.id.thumbnail);
thumbnailView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Remove the GlobalOnLayout Listener so it only fires once.
thumbnailView.getViewTreeObserver().removeGlobalOnLayoutListener(this)
// Find the images Height to Width ratio
Drawable image = getResources().getDrawable(R.drawable.thumbnail);
float heighToWidthRatio = image.getIntrinsicWidth()/image.getIntrinsicHeight();
// Use this ratio to discover the ratio of the ImageView to allow it to perfectly contain the image.
int height = thumbnailView.getHeight();
thumbnailView.setLayoutParams(new LayoutParams(
(int) (height * heighToWidthRatio), height));
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5156 次 |
| 最近记录: |