Android(Java)中如何在GridView中使ImageView呈圆形?
创始人
2024-10-13 07:30:53
0
  1. 首先,定义一个自定义的ImageView类RoundedImageView。代码如下:

public class RoundedImageView extends ImageView {

public RoundedImageView(Context context) {
    super(context);
}

public RoundedImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onDraw(Canvas canvas) {
    Path clipPath = new Path();
    int w = getWidth();
    int h = getHeight();
    clipPath.addCircle(w / 2, h / 2, Math.min(w, h) / 2, Path.Direction.CW);
    canvas.clipPath(clipPath);
    super.onDraw(canvas);
}

}

  1. 在布局文件中,使用自定义的RoundedImageView替代普通的ImageView。

  1. 在代码中,使用Picasso或Glide图片库加载图片到RoundedImageView中,使其呈现为圆形。代码如下:

RoundedImageView imageView = (RoundedImageView) convertView.findViewById(R.id.image_item); Picasso.with(context) .load(imageUrl) .placeholder(R.mipmap.ic_launcher) .error(R.mipmap.ic_launcher) .fit() .centerCrop() .transform(new CircleTransform()) .into(imageView);

注意,这里使用了名为CircleTransform的自定义Picasso转换类,代码如下:

public class CircleTransform implements Transformation { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); if (squaredBitmap != source) { source.recycle(); } Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig()); Canvas canvas = new Canvas(bitmap); Paint paint = new Paint(); BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); paint.setShader(shader); paint.setAntiAlias(true); float r = size / 2f; canvas.drawCircle(r, r, r, paint); squaredBitmap.recycle(); return bitmap; }

@Override
public String key() {
    return "circle";

相关内容

热门资讯

2024教程!wepoker怎... 1、2024教程!wepoker怎么增加运气,pokemmo脚本辅助下载,高科技教程(有挂辅助)。2...
盘点一款!We poker辅助... 盘点一款!We poker辅助器下载,hhpoker到底可以作弊吗,透明挂教程(有挂神器)是由北京得...
玩家必看攻略!we-poker... 《玩家必看攻略!we-poker是什么软件,aapoker怎么开辅助器,插件教程(有挂技巧)》 aa...
玩家必看科普!约局吧开挂神器是... 玩家必看科普!约局吧开挂神器是真的吗,wepoker好友助力码,力荐教程(有挂技巧);《WPK辅助透...
交流学习经验!werplan辅... 自定义wepoker辅助真的假的系统规律,只需要输入自己想要的开挂功能,一键便可以生成出微扑克专用辅...
教程辅助!wepoker有没有... 教程辅助!wepoker有没有挂,hhpoker是正品吗,技巧教程(有挂软件);《WPK辅助透视》‌...
最新通报!wepoker怎么设... 1、最新通报!wepoker怎么设置房间,wepoker辅助真的假的,AA德州教程(有挂教程)(UU...
热点讨论!hhpoker辅助器... 热点讨论!hhpoker辅助器,hh poker透视器下载,高科技教程(有挂透明);人气非常高,ai...
重大消息!wepoker透视苹... 重大消息!wepoker透视苹果系统,wepoker怎么设置盖牌,必胜教程(有挂技巧);人气非常高,...
交流学习经验!wepoker免... 交流学习经验!wepoker免费辅助器,hhpoker免费辅助器,辅助教程(有挂攻略);人气非常高,...