因此,在尝试将图像正确地扩展到宽度之后出现了大量的挫折感,我意识到我的真正问题是setImageResource与setImageDrawable(我正在尝试使用)的行为不同。下面的XML给出了完美的宽度,宽高比拉伸图像与setImageResource,但与setImageDrawable图像没有拉伸到宽度,任何建议我应该如何处理问题?我使用setImageDrawable,因为我从互联网上获取图像的替代品是受欢迎的:)
<ImageView
android:id="@+id/item_image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
哦,我尝试过scaletype,给出最佳结果的是scalecrop,但它不是所需的作物。
答案 0 :(得分:1)
这个问题真的很陈旧但是如果遇到任何问题,这个问题与不是一个错误有关,而是在18之前的Android版本中做出错误的实施决定。如果你的目标是18岁以上你可能会赢得#39 ;看到这个问题。不过,我目前的目标是16岁的企业级平板电脑。
解决方案是创建一个ImageView的超类,它覆盖onMeasure以强制执行宽高比:
class MyImageView extends ImageView {
public MyImageView(Context context) {
super(context);
}
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
float iwidth = (float) View.MeasureSpec.getSize(widthMeasureSpec);
float swidth = (float) getDrawable().getIntrinsicWidth();
float sheight = (float) getDrawable().getIntrinsicHeight();
float iheight = sheight / swidth * iwidth;
setMeasuredDimension((int)iwidth, (int)iheight);
}
}
在你的布局中:
<com.mypackage.MyImageView layout_width="match_parent" etc... />
如果您定位Android 18+,adjustViewBounds应按预期工作。
答案 1 :(得分:0)
您只需在xml ImageView中进行更改
机器人:layout_width = “FILL_PARENT”
机器人:layout_hight = “FILL_PARENT”
答案 2 :(得分:0)
我发现的一个修复是使用位图,因为setImageBitmap显然与setImageResource类似。我仍然愿意接受其他建议。
答案 3 :(得分:0)
您的图片视图的宽度为fill_parent,因此如果图片的宽度不够,则会被拉伸。如果您不想使用fill_parent,只需替换宽度“wrap_content”。
<ImageView
android:id="@+id/item_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>