您的位置:首页 > 移动开发 > Android开发

Android 显示图片缩放的注意事项

2013-04-17 11:14 281 查看
最近项目有个需求,在ImagView显示一张图片的预览效果,要求该图片宽度占对话框宽度的4/5,高度与宽度成比例缩放(不能变形),看下面的示意图



图片宽度占对话框的4/5容易解决,使用weight属性就可以了,代码如下

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/et_messages"
>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/iv_picture"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginRight="5dip"
android:scaleType="centerInside"
android:layout_weight="4"
/>
</LinearLayout>


Java 代码
ImageView ivPicture = (ImageView)dialog.findViewById(R.id.iv_picture);
try {
bitmap = ImageUtils.getBitmapFromAssets(context, "WS_MainMenuCommonShared_iphone.png");

}catch(IOException e) {
e.printStackTrace();
}
ivPicture.setBackgroundDrawable(new BitmapDrawable(bitmap));

大家可以看到,图片缩放是 android:scaleType="centerInside" ,原以为这样就大功告成,可是结果并没有像想象的那样,图片没有按预期的方式缩放。

Google了一下,原来使用android:scaleType="centerInside" 时,图片不能使用设置背景的方式,最后一行代码改为

ivPicture.setImageBitmap(bitmap);


就可以了,效果刚刚好。这里之所以把这个问题记下来,其实想汇总一些ImageView使用时的一些特别之处,以后还会继续补充,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息