需求:固定大小的ImageView,但是大小不固定的ImageBitmap,想要使用这个大小不一的ImageBitmap填充满这个ImageView,从而让整个视图看起来整齐

这个可以直接在layout.xml这样实现的

<ImageView android:id="@+id/foodItem_foodImg"android:src="@drawable/food_img_na"android:layout_width="277dip"android:layout_height="300dip"android:scaleType="centerCrop"/>

这里边的centerCrop的意思就是: Scale the image uniformly (maintain the image's aspect ratio) so that both dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding). 英语撇,就不翻译了,见谅。

参见:Developer.android.com


但是这样的图片看起来是有直角的,是生硬的,给用户一种强硬的感觉。

如果我们把图片的4个角都给他倒圆角,就看起来圆润一些,不至于那么伤人,那么生硬。

但是我想了很久,也找了很久,也没有找到直接操作ImageBitmap来实现:centerCrop效果 + 圆角效果

后来想到直接在在ImageView.onDraw的时候,给他画出圆角来,这样这个ImageView里面的ImageBitmap也有圆角的效果了

代码是这样实现的


import android.content.Context;import android.graphics.Canvas;import android.graphics.Path;import android.graphics.RectF;import android.util.AttributeSet;import android.widget.ImageView;public class RoundCornerImageView extends ImageView {public RoundCornerImageView(Context context) {super(context);}public RoundCornerImageView(Context context, AttributeSet attrs) {super(context, attrs);}public RoundCornerImageView(Context context, AttributeSet attrs,int defStyle) {super(context, attrs, defStyle);}@Overrideprotected void onDraw(Canvas canvas) {Path clipPath = new Path();int w = this.getWidth();int h = this.getHeight();clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);canvas.clipPath(clipPath);super.onDraw(canvas);}}

下面这行代码就能画出圆角效果,10度的角
clipPath.addRoundRect(new RectF(0, 0, w, h), 10.0f, 10.0f, Path.Direction.CW);

在layout.xml中直接使用RoundCornerImageView就会出现圆角的ImageView效果

<cn.hus.app.ui.utils.RoundCornerImageView android:id="@+id/foodItem_foodImg"android:src="@drawable/food_img_na"android:layout_width="277dip"android:layout_height="300dip"android:scaleType="centerCrop"/>


使用请谨慎,本例没有考虑性能方面的东西,谨慎再谨慎。

更多相关文章

  1. Android自定义View实现HTML图文环绕效果
  2. Android(安卓)动画之AlphaAnimation应用详解
  3. Android实现快递物流时间轴效果
  4. Android(安卓)使用SpannableString显示复合文本
  5. Android(安卓)OpenGLES 3.0 开发极简教程
  6. Android仿QQ复制昵称效果
  7. Android重写HorizontalScrollView仿ViewPager效果
  8. Android滑动效果入门篇———ViewFlipper实现滑动效果
  9. datetimepicker一个不错的日历android特效

随机推荐

  1. android 笔记 --- Bitmap与Drawable转换
  2. Android通知栏点击通知消失
  3. Android的屏幕多样性支持
  4. cocos2dx 使用jni方法获取android mac地
  5. Unity3D Android
  6. APP签名打包时遇到的问题
  7. Android(安卓)删除文件夹以及文件夹中的
  8. Android(安卓)--Intent意图的讲解
  9. Android(安卓)锁屏 临时屏蔽
  10. Android(安卓)ListView+ArrayAdapter简单