【问题标题】:How to round an image with Glide library?如何使用 Glide 库对图像进行四舍五入?
【发布时间】:2014-10-06 09:06:35
【问题描述】:

那么,有人知道如何使用 Glide 显示带有圆角的图像吗? 我正在使用 Glide 加载图像,但我不知道如何将舍入参数传递给该库。

我需要像下面的例子那样显示图像:

【问题讨论】:

  • 我已经使用github.com/hdodenhof/CircleImageView 进行旋转图像视图
  • 我知道如何将 Glide 库与 CircleImageView 一起使用,但我搜索了仅使用 Glide 库的可能方法。在 Glide lib 中有任何方法可以执行此操作还是不受支持?

标签: android android-glide


【解决方案1】:

滑翔 V4:

    Glide.with(context)
        .load(url)
        .circleCrop()
        .into(imageView);

滑翔 V3:

您可以将RoundedBitmapDrawable 用于带有 Glide 的圆形图像。不需要自定义 ImageView。

 Glide.with(context).load(url).asBitmap().centerCrop().into(new BitmapImageViewTarget(imageView) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(context.getResources(), resource);
            circularBitmapDrawable.setCircular(true);
            imageView.setImageDrawable(circularBitmapDrawable);
        }
    });

【讨论】:

  • 不过,这不会创建边框。
  • @jimmy0251 不,你不能。滑动可绘制对象不是 BitmapDrawables。它们是从占位符交叉淡入淡出到真实图像的 transitiondrawables 和 glidedrawables。 RoundedBitmapDrawable 无法处理。
  • 用可绘制的椭圆形设置背景。并为 imageview 提供填充以创建边框。
  • 如果您遇到问题,请检查 Roman Samoylenko 的下一个解决方案。
  • 你可能指的是.circleCrop()而不是.circleCrop()
【解决方案2】:

检查此post, glide vs picasso...
编辑:链接的帖子并未指出库中的重要区别。 Glide 会自动进行回收。请参阅TWiStErRob's comment 了解更多信息。

Glide.with(this).load(URL).transform(new CircleTransform(context)).into(imageView);

public static class CircleTransform extends BitmapTransformation {
    public CircleTransform(Context context) {
        super(context);
    }

    @Override protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return circleCrop(pool, toTransform);
    }

    private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        int size = Math.min(source.getWidth(), source.getHeight());
        int x = (source.getWidth() - size) / 2;
        int y = (source.getHeight() - size) / 2;

        // TODO this could be acquired from the pool too
        Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);

        Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);
        float r = size / 2f;
        canvas.drawCircle(r, r, r, paint);
        return result;
    }

    @Override public String getId() {
        return getClass().getName();
    }
} 

【讨论】:

  • 听起来很有趣。它是否适用于 API 21 的大纲?
  • 嗯,那我可能会用这个。我将尝试简单地使用自定义视图,但我不想创建第二个位图:)。此外,您应该始终使用位图池以尝试从那里获取位图 :)
  • 小心使用public String getId() 代码中显示的方式,因为它为所有图像返回相同的 id,因此滑翔可能会设置旧的圆形图像,而无需转换它会设置正确的图像!我不知道 glide 是如何工作的,但它似乎缓存了图像转换(为了避免我假设的硬计算)。并且id被用作转换后的图像的id。我向构造函数添加了一个图像的 url,并提到了返回结果 id 的方法,例如:this.id = String.format("%s:%s",this.getClass().getSimpleName(),id);
  • Stan 对 Transformation id 的唯一要求是它们在所有 Transformation 中是唯一的,所以这里的用法是正确的。缓存键将包括源 id 和转换 id,因此转换 id 是混合而不是替换。见github.com/bumptech/glide/wiki/…
  • 有没有办法将转换应用于占位符?
【解决方案3】:

最简单的方法(需要 Glide 4.x.x)

Glide.with(context).load(uri).apply(RequestOptions.circleCropTransform()).into(imageView)

【讨论】:

  • 这甚至无法编译... RequestOptions()?
  • @RafaelLima 它是用 Kotlin 编写的。
  • 注意,.apply() 跟在 .load() 之后。
  • 是 RequestOptions.circleCropTransform(),而不是 RequestOptions()。
  • 你需要写 Glide.with(context).load(uri).apply(circleCrop()).into(imageView) 看看apply函数。
【解决方案4】:

试试这个方法

代码

Glide.with(this)
    .load(R.drawable.thumbnail)
    .bitmapTransform(new CropCircleTransformation(this))
    .into(mProfile);

XML

<ImageView
  android:id="@+id/img_profile"
  android:layout_width="76dp"
  android:layout_height="76dp"
  android:background="@drawable/all_circle_white_bg"
  android:padding="1dp"/>

all_circle_white_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item>
    <shape android:shape="oval">
      <solid android:color="@android:color/white"/>
  </shape>
  </item>
</selector>

【讨论】:

    【解决方案5】:

    它非常简单,我已经看到 Glide 库它非常好的库和基于 volley Google 库的文章

    将此库用于圆形图像视图

    https://github.com/hdodenhof/CircleImageView

    现在

    //简单的视图:

     @Override
     public void onCreate(Bundle savedInstanceState) {
      ...
    
      CircleImageView civProfilePic = (CircleImageView)findViewById(R.id.ivProfile);
      Glide.load("http://goo.gl/h8qOq7").into(civProfilePic);
    }
    

    //对于一个列表:

    @Override
    public View getView(int position, View recycled, ViewGroup container) {
    final ImageView myImageView;
     if (recycled == null) {
        myImageView = (CircleImageView) inflater.inflate(R.layout.my_image_view,
                container, false);
    } else {
        myImageView = (CircleImageView) recycled;
    }
    
    String url = myUrls.get(position);
    
    Glide.load(url)
        .centerCrop()
        .placeholder(R.drawable.loading_spinner)
        .animate(R.anim.fade_in)
        .into(myImageView);
    
      return myImageView;
    }
    

    在 XML 中

    <de.hdodenhof.circleimageview.CircleImageView
       android:id="@+id/ivProfile
       android:layout_width="160dp"
       android:layout_height="160dp"
       android:layout_centerInParent="true"
       android:src="@drawable/hugh"
       app:border_width="2dp"
       app:border_color="@color/dark" />
    

    【讨论】:

    • 就像之前的答案评论中提到的那样,这种方式也不能很好地工作。至少对于 'de.hdodenhof:circleimageview:1.2.2' + 'com.github.bumptech.glide:glide:3.5.2'。检查和双重检查。 glide 3.4.+ 和 circleimageview 1.2.1 也存在同样的问题
    • +1 表示 .centerCrop()。使用DiamondImageView plus .asBitmap() 为我工作。
    • 需要在滑行时调用 .dontAnimate(),这是不可接受的
    【解决方案6】:

    其他解决方案对我不起作用。我发现它们都有明显的缺点:

    • 使用滑行变换的解决方案不适用于占位符
    • 使用圆形图像视图的解决方案不适用于动画(即淡入淡出)
    • 使用剪辑其子级的父级的通用方法(即接受的答案here)的解决方案不适用于 glide

    真正有趣的是,在摸索之后,我发现了Fresco library page about rounded corners and circles,他们在其中列出了基本相同的限制并以声明结尾:

    对于 Android 上的圆角没有真正好的解决方案,人们必须在上述权衡之间做出选择

    令人难以置信的是,此时我们仍然没有真正的解决方案。我有一个基于上面链接的替代解决方案。这种方法的缺点是它假设您的背景是纯色(角落不是真正透明的)。你可以这样使用它:

    <RoundedCornerLayout ...>
        <ImageView ...>
    </RoundedCornerLayout>
    

    要点是here,完整代码在这里:

    public class RoundedCornerLayout extends RelativeLayout {
        private Bitmap maskBitmap;
        private Paint paint;
        private float cornerRadius;
    
        public RoundedCornerLayout(Context context) {
            super(context);
            init(context, null, 0);
        }
    
        public RoundedCornerLayout(Context context, AttributeSet attrs) {
            super(context, attrs);
            init(context, attrs, 0);
        }
    
        public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init(context, attrs, defStyle);
        }
    
        private void init(Context context, AttributeSet attrs, int defStyle) {
            paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    
            setWillNotDraw(false);
        }
    
        @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);
    
            if (maskBitmap == null) {
                // This corner radius assumes the image width == height and you want it to be circular
                // Otherwise, customize the radius as needed
                cornerRadius = canvas.getWidth() / 2;
                maskBitmap = createMask(canvas.getWidth(), canvas.getHeight());
            }
    
            canvas.drawBitmap(maskBitmap, 0f, 0f, paint);
        }
    
        private Bitmap createMask(int width, int height) {
            Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(mask);
    
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
            paint.setColor(Color.WHITE); // TODO set your background color as needed
    
            canvas.drawRect(0, 0, width, height, paint);
    
            paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
            canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint);
    
            return mask;
        }
    }
    

    【讨论】:

      【解决方案7】:

      现在在 Glide V4 中你可以直接使用 CircleCrop()

      Glide.with(fragment)
        .load(url)
        .circleCrop()
        .into(imageView);
      

      内置类型

      • 中心裁剪
      • 健身中心
      • 圆形裁剪

      【讨论】:

        【解决方案8】:

        根据this的回答,两种语言最简单的方法是:

        科特林:

        Glide.with(context).load(uri).apply(RequestOptions().circleCrop()).into(imageView)
        

        Java:

        Glide.with(context).load(uri).apply(new RequestOptions().circleCrop()).into(imageView)
        

        这适用于 Glide 4.X.X

        【讨论】:

          【解决方案9】:

          使用这个转换,它会正常工作。

          public class CircleTransform extends BitmapTransformation {
          public CircleTransform(Context context) {
              super(context);
          }
          
          @Override
          protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
              return circleCrop(pool, toTransform);
          }
          
          private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
              if (source == null) return null;
          
              int borderColor = ColorUtils.setAlphaComponent(Color.WHITE, 0xFF);
              int borderRadius = 3;
          
              int size = Math.min(source.getWidth(), source.getHeight());
              int x = (source.getWidth() - size) / 2;
              int y = (source.getHeight() - size) / 2;
          
              // TODO this could be acquired from the pool too
              Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
              if (squared != source) {
                  source.recycle();
              }
          
              Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
              if (result == null) {
                  result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
              }
          
              Canvas canvas = new Canvas(result);
              Paint paint = new Paint();
              paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
              paint.setAntiAlias(true);
              float r = size / 2f;
              canvas.drawCircle(r, r, r, paint);
          
              // Prepare the background
              Paint paintBg = new Paint();
              paintBg.setColor(borderColor);
              paintBg.setAntiAlias(true);
          
              // Draw the background circle
              canvas.drawCircle(r, r, r, paintBg);
          
              // Draw the image smaller than the background so a little border will be seen
              canvas.drawCircle(r, r, r - borderRadius, paint);
          
              squared.recycle();
          
              return result;
          }
          
          @Override
          public String getId() {
              return getClass().getName();
          }} 
          

          【讨论】:

            【解决方案10】:

            对于Glide 4.x.x

            使用

            Glide
              .with(context)
              .load(uri)
              .apply(
                  RequestOptions()
                    .circleCrop())
              .into(imageView)
            

            来自 doc 表示

            圆形图片:CircularImageView/CircularImageView/RoundedImageView 是 已知有 issues 与 TransitionDrawable (.crossFade() 与 .thumbnail() 或 .placeholder()) 和动画 GIF,使用 BitmapTransformation(.circleCrop() 将在 v4 中可用)或 .dontAnimate() 解决问题

            【讨论】:

              【解决方案11】:

              Roman Samoylenko 的回答是正确的,只是功能发生了变化。 正确答案是

              Glide.with(context)
                              .load(yourImage)
                              .apply(RequestOptions.circleCropTransform())
                              .into(imageView);
              

              【讨论】:

                【解决方案12】:

                我找到了一种简单的解决方案,可以在要设置颜色的图像视图上添加边框或在图像上添加渐变。

                步骤:

                1. 采用一帧布局并添加两个图像。您可以根据需要设置大小。对于 imgPlaceHolder ,您需要一个要设置的白色图像或颜色。

                        <ImageView
                            android:id="@+id/imgPlaceHolder"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:layout_gravity="center"
                            android:src="@drawable/white_bg"/>
                
                        <ImageView
                            android:id="@+id/imgPic"
                            android:layout_width="190dp"
                            android:layout_height="190dp"
                            android:layout_gravity="center"
                            android:src="@drawable/image01"/>
                    </FrameLayout>
                
                1. 将此代码放在 xml 文件中后,将下面的行放入 java 文件中。

                  Glide.with(this).load(R.drawable.image01).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPic) {
                      @Override
                      protected void setResource(Bitmap resource) {
                          RoundedBitmapDrawable circularBitmapDrawable =
                                  RoundedBitmapDrawableFactory.create(getResources(), resource);
                          circularBitmapDrawable.setCircular(true);
                          imageView.setImageDrawable(circularBitmapDrawable);
                      }
                  });
                  
                  Glide.with(this).load(R.drawable.white_bg).asBitmap().centerCrop().into(new BitmapImageViewTarget(imgPlaceHolder) {
                      @Override
                      protected void setResource(Bitmap resource) {
                          RoundedBitmapDrawable circularBitmapDrawable =
                                  RoundedBitmapDrawableFactory.create(getResources(), resource);
                          circularBitmapDrawable.setCircular(true);
                          imgTemp2.setImageDrawable(circularBitmapDrawable);
                      }
                  });
                  

                这将使 imageview 的边框变得简单,没有任何额外的填充和边距。

                注意 :白色图像是强制性的边框,否则将不起作用。

                编码愉快:)

                【讨论】:

                  【解决方案13】:

                  通过 glide 库,您可以使用以下代码:

                  Glide.with(context)
                      .load(imageUrl)
                      .asBitmap()
                      .placeholder(R.drawable.user_pic)
                      .centerCrop()
                      .into(new BitmapImageViewTarget(img_profPic) {
                          @Override
                          protected void setResource(Bitmap resource) {
                              RoundedBitmapDrawable circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.getResources(), resource);
                  
                              circularBitmapDrawable.setCircular(true);
                              img_profPic.setImageDrawable(circularBitmapDrawable);
                          }
                      });
                  

                  【讨论】:

                  • 你也可以通过 glid 库制作圆角图片。
                  【解决方案14】:

                  圆形裁剪 + 占位符 + 淡入淡出

                   Glide.with(context!!)
                                      .load(randomImage)
                                      .apply(RequestOptions.bitmapTransform(CircleCrop()).error(R.drawable.nyancat_animated))
                                      .transition(DrawableTransitionOptions()
                                              .crossFade())
                                      .into(picture)
                  

                  【讨论】:

                    【解决方案15】:

                    我之前一直在寻找它,我以最简单的方式做到了,希望你会喜欢。

                     //crete this method into your Utils class and call this method wherever you want to use.
                        //you can set these placeHolder() and error() image static as well. I made it as comment inside this method, then no need to use [placeHolderUrl and errorImageUrl] parameters. remove it from this method.
                        public static void loadImage(final Activity context, ImageView imageView, String url, int placeHolderUrl, int errorImageUrl) {
                            if (context == null || context.isDestroyed()) return;
                    
                            //placeHolderUrl=R.drawable.ic_user;
                            //errorImageUrl=R.drawable.ic_error;
                                Glide.with(context) //passing context
                                        .load(getFullUrl(url)) //passing your url to load image.
                                        .placeholder(placeHolderUrl) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
                                        .error(errorImageUrl)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
                                        .diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
                                        .transform(new CircleTransform(context))//this CircleTransform class help to crop an image as circle.
                                        .animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
                                        .fitCenter()//this method help to fit image into center of your ImageView
                                        .into(imageView); //pass imageView reference to appear the image.
                        } 
                    

                    CircleTransform.java

                      public class CircleTransform extends BitmapTransformation {
                        public CircleTransform(Context context) {
                            super(context);
                    
                            if(context==null)
                                return;
                        }
                    
                        private static Bitmap circleCrop(BitmapPool pool, Bitmap source) {
                            if (source == null) return null;
                    
                            int size = Math.min(source.getWidth(), source.getHeight());
                            int x = (source.getWidth() - size) / 2;
                            int y = (source.getHeight() - size) / 2;
                    
                    
                            Bitmap squared = Bitmap.createBitmap(source, x, y, size, size);
                    
                            Bitmap result = pool.get(size, size, Bitmap.Config.ARGB_8888);
                            if (result == null) {
                                result = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
                            }
                    
                            Canvas canvas = new Canvas(result);
                            Paint paint = new Paint();
                            paint.setShader(new BitmapShader(squared, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
                            paint.setAntiAlias(true);
                            float r = size / 2f;
                            canvas.drawCircle(r, r, r, paint);
                            return result;
                        }
                    
                        @Override
                        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
                            return circleCrop(pool, toTransform);
                        }
                    
                        @Override
                        public String getId() {
                            return getClass().getName();
                        }
                    }
                    

                    fade_in.xml 用于淡入动画。

                        <set xmlns:android="http://schemas.android.com/apk/res/android">
                    <!--THIS ANIMATION IS USING FOR FADE IN -->
                    
                    <alpha
                        android:duration="800"
                        android:fromAlpha="0.0"
                        android:interpolator="@android:anim/decelerate_interpolator"
                        android:toAlpha="1.0" />
                    

                    终于调用了这个方法。

                    Utils.loadImage(YourClassName.this,mImageView,url,R.drawable.ic_user,R.drawable.ic_error);
                    

                    【讨论】:

                      【解决方案16】:

                      您可以简单地调用具有cornerType 枚举输入的RoundedCornersTransformation 构造函数。像这样:

                      Glide.with(context)
                                  .load(bizList.get(position).getCover())
                                  .bitmapTransform(new RoundedCornersTransformation(context,20,0, RoundedCornersTransformation.CornerType.TOP))
                                  .into(holder.bizCellCoverImg);
                      

                      但首先您必须将Glide Transformations 添加到您的项目中。

                      【讨论】:

                        【解决方案17】:

                        这是在 Glide 中圆形裁剪位图的更模块化和更简洁的方法:

                        1. 通过扩展 BitmapTransformation 创建自定义转换,然后重写 transform 方法,如下所示:

                        对于 Glide 4.x.x

                        public class CircularTransformation extends BitmapTransformation {
                        
                        @Override
                        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
                            RoundedBitmapDrawable circularBitmapDrawable =
                                    RoundedBitmapDrawableFactory.create(null, toTransform);
                            circularBitmapDrawable.setCircular(true);
                            Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
                            Canvas canvas = new Canvas(bitmap);
                            circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
                            circularBitmapDrawable.draw(canvas);
                            return bitmap;
                            }
                        
                        @Override
                        public void updateDiskCacheKey(MessageDigest messageDigest) {}
                        
                        }
                        

                        对于 Glide 3.x.x

                        public class CircularTransformation extends BitmapTransformation {
                        
                        @Override
                        protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
                            RoundedBitmapDrawable circularBitmapDrawable =
                                    RoundedBitmapDrawableFactory.create(null, toTransform);
                            circularBitmapDrawable.setCircular(true);
                            Bitmap bitmap = pool.get(outWidth, outHeight, Bitmap.Config.ARGB_8888);
                            Canvas canvas = new Canvas(bitmap);
                            circularBitmapDrawable.setBounds(0, 0, outWidth, outHeight);
                            circularBitmapDrawable.draw(canvas);
                            return bitmap;
                            }
                        
                        @Override
                        public String getId() {
                            // Return some id that uniquely identifies your transformation.
                            return "CircularTransformation";
                            }
                        
                        }
                        
                        1. 然后在 Glide builder 中设置你需要的地方:
                        Glide.with(yourActivity)
                           .load(yourUrl)
                           .asBitmap()
                           .transform(new CircularTransformation())
                           .into(yourView);
                        

                        希望这会有所帮助:)

                        【讨论】:

                          【解决方案18】:
                          private void setContactImage(@NonNull ViewHolder holder, ClsContactDetails clsContactDetails) {
                              Glide.with(context).load(clsContactDetails.getPic())
                                  .apply(new RequestOptions().centerCrop().circleCrop().placeholder(R.mipmap.ic_launcher)).into(holder.ivPersonImage);
                          }
                          

                          【讨论】:

                            【解决方案19】:
                            implementation 'com.github.bumptech.glide:glide:4.8.0'
                            annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
                            
                            
                            RequestOptions options=new RequestOptions();
                                    options.centerCrop().placeholder(getResources().getDrawable(R.drawable.user_placeholder));
                                    Glide.with(this)
                                            .load(preferenceSingleTon.getImage())
                                            .apply(options)
                                            .into(ProfileImage);
                            

                            【讨论】:

                              【解决方案20】:

                              Glide 版本 4.6.1

                              Glide.with(context)
                              .load(url)
                              .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                              .into(imageView);
                              

                              【讨论】:

                                【解决方案21】:

                                在这种情况下,我需要添加阴影,而 imageView 高程不起作用

                                实现“com.github.bumptech.glide:glide:4.10.0”

                                XML

                                <FrameLayout
                                    android:id="@+id/fl_image"
                                    android:layout_width="60dp"
                                    android:layout_height="60dp"
                                    android:layout_margin="10dp"
                                    android:background="@drawable/card_circle_background"
                                    android:elevation="8dp">
                                
                                    <ImageView
                                        android:id="@+id/iv_item_employee"
                                        android:layout_width="60dp"
                                        android:layout_height="60dp"
                                        tools:background="@color/colorPrimary" />
                                </FrameLayout>
                                

                                可绘制形状

                                <?xml version="1.0" encoding="utf-8"?>
                                <shape xmlns:android="http://schemas.android.com/apk/res/android"
                                       android:shape="oval">
                                     <solid android:color="@color/white"/>
                                </shape>
                                

                                滑翔配置

                                Glide.with(this)
                                    .asBitmap()
                                    .load(item.image)
                                    .apply(RequestOptions.circleCropTransform())
                                    .into(iv_item_employee)
                                

                                【讨论】:

                                  【解决方案22】:

                                  就我而言; .apply(RequestOptions.circleCropTransform()) (4.11) 无效。因为我正在使用 ImageButton 进行尝试。当我使用(可点击的)ImageView 进行更改时,它可以正常工作并且看起来像我想要的那样。

                                  【讨论】:

                                    【解决方案23】:

                                    您必须使用CircularImageView 来显示该类型的图像...

                                    您正在使用 Glide library 用于加载图像..

                                    在您的项目中创建一个 ClassFile 并在 Imageview 中加载它...您将获得所需的结果...

                                    尝试以下代码...

                                    XML

                                     <com.yourpackage.CircularImageView
                                        android:id="@+id/imageview"
                                        android:layout_width="96dp"
                                        android:layout_height="96dp"
                                        app:border="true"
                                        app:border_width="3dp"
                                        app:border_color="@color/white"
                                        android:src="@drawable/image" />
                                    

                                    CircularImageView.java

                                    public class CircularImageView extends ImageView {
                                        private int borderWidth;
                                        private int canvasSize;
                                        private Bitmap image;
                                        private Paint paint;
                                        private Paint paintBorder;
                                    
                                        public CircularImageView(final Context context) {
                                            this(context, null);
                                        }
                                    
                                        public CircularImageView(Context context, AttributeSet attrs) {
                                            this(context, attrs, R.attr.circularImageViewStyle);
                                        }
                                    
                                        public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
                                            super(context, attrs, defStyle);
                                    
                                            // init paint
                                            paint = new Paint();
                                            paint.setAntiAlias(true);
                                    
                                            paintBorder = new Paint();
                                            paintBorder.setAntiAlias(true);
                                    
                                            // load the styled attributes and set their properties
                                            TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView, defStyle, 0);
                                    
                                            if(attributes.getBoolean(R.styleable.CircularImageView_border, true)) {
                                                int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics().density + 0.5f);
                                                setBorderWidth(attributes.getDimensionPixelOffset(R.styleable.CircularImageView_border_width, defaultBorderSize));
                                                setBorderColor(attributes.getColor(R.styleable.CircularImageView_border_color, Color.WHITE));
                                            }
                                    
                                            if(attributes.getBoolean(R.styleable.CircularImageView_shadow, false))
                                                addShadow();
                                        }
                                    
                                        public void setBorderWidth(int borderWidth) {
                                            this.borderWidth = borderWidth;
                                            this.requestLayout();
                                            this.invalidate();
                                        }
                                    
                                        public void setBorderColor(int borderColor) {
                                            if (paintBorder != null)
                                                paintBorder.setColor(borderColor);
                                            this.invalidate();
                                        }
                                    
                                        public void addShadow() {
                                            setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
                                            paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
                                        }
                                    
                                        @Override
                                        public void onDraw(Canvas canvas) {
                                            // load the bitmap
                                            image = drawableToBitmap(getDrawable());
                                    
                                            // init shader
                                            if (image != null) {
                                    
                                                canvasSize = canvas.getWidth();
                                                if(canvas.getHeight()<canvasSize)
                                                    canvasSize = canvas.getHeight();
                                    
                                                BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
                                                paint.setShader(shader);
                                    
                                                // circleCenter is the x or y of the view's center
                                                // radius is the radius in pixels of the cirle to be drawn
                                                // paint contains the shader that will texture the shape
                                                int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
                                                canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
                                                canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);
                                            }
                                        }
                                    
                                        @Override
                                        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                                            int width = measureWidth(widthMeasureSpec);
                                            int height = measureHeight(heightMeasureSpec);
                                            setMeasuredDimension(width, height);
                                        }
                                    
                                        private int measureWidth(int measureSpec) {
                                            int result = 0;
                                            int specMode = MeasureSpec.getMode(measureSpec);
                                            int specSize = MeasureSpec.getSize(measureSpec);
                                    
                                            if (specMode == MeasureSpec.EXACTLY) {
                                                // The parent has determined an exact size for the child.
                                                result = specSize;
                                            } else if (specMode == MeasureSpec.AT_MOST) {
                                                // The child can be as large as it wants up to the specified size.
                                                result = specSize;
                                            } else {
                                                // The parent has not imposed any constraint on the child.
                                                result = canvasSize;
                                            }
                                    
                                            return result;
                                        }
                                    
                                        private int measureHeight(int measureSpecHeight) {
                                            int result = 0;
                                            int specMode = MeasureSpec.getMode(measureSpecHeight);
                                            int specSize = MeasureSpec.getSize(measureSpecHeight);
                                    
                                            if (specMode == MeasureSpec.EXACTLY) {
                                                // We were told how big to be
                                                result = specSize;
                                            } else if (specMode == MeasureSpec.AT_MOST) {
                                                // The child can be as large as it wants up to the specified size.
                                                result = specSize;
                                            } else {
                                                // Measure the text (beware: ascent is a negative number)
                                                result = canvasSize;
                                            }
                                    
                                            return (result + 2);
                                        }
                                    
                                        public Bitmap drawableToBitmap(Drawable drawable) {
                                            if (drawable == null) {
                                                return null;
                                            } else if (drawable instanceof BitmapDrawable) {
                                                return ((BitmapDrawable) drawable).getBitmap();
                                            }
                                    
                                            Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
                                                    drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                                            Canvas canvas = new Canvas(bitmap);
                                            drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
                                            drawable.draw(canvas);
                                    
                                            return bitmap;
                                        }
                                    }
                                    

                                    注意:

                                    你可以使用

                                    CircularImageView imgIcon = (CircularImageView)findViewById(R.id.imageview);
                                    

                                    ImageView imgIcon = (ImageView)findViewById(R.id.imageview);
                                    

                                    它不会影响您的其他库...不必更改您的代码以下载图像或其他任何内容... 它也可以简单地使用 XML 来定义..

                                    【讨论】:

                                    • 我已经尝试过 Glide + CircularImageView(和 RoundedImageView),如果你开始使用占位符(当你的图像被下载时)和外观动画,它就不能很好地工作。毕加索没有这个问题。您可以在这里了解更多信息:github.com/vinc3m1/RoundedImageView/issues/76
                                    • 在 Glide 调用中使用 .asBitmap 就可以了。
                                    • 需要在滑行时调用 .dontAnimate(),这是不可接受的
                                    【解决方案24】:
                                                    Glide.with(MainActivity.this)
                                                            .load(personPhoto)
                                                            .transition(withCrossFade(500))
                                                            .apply(RequestOptions.circleCropTransform())
                                                            .thumbnail(0.5f)
                                                            .into(imageView);
                                    
                                                
                                    

                                    【讨论】:

                                      【解决方案25】:

                                      不要附加太多placeholder()、transition()等函数,只要像这段代码一样简单,就可以工作了。

                                                              Glide.with(mContext)
                                                                  .load(datas.getUser_img())
                                                                  .centerCrop()
                                                                  .into(ivAvator);
                                      

                                      【讨论】:

                                        【解决方案26】:

                                        简单的解决方案 通过使用这个库 实施 'de.hdodenhof:circleimageview:3.1.0'

                                        <de.hdodenhof.circleimageview.CircleImageView
                                        xmlns:app="http://schemas.android.com/apk/res-auto"
                                        android:id="@+id/profile_image"
                                        android:layout_width="96dp"
                                        android:layout_height="96dp"
                                        android:src="@drawable/profile"
                                        app:civ_border_width="2dp"
                                        app:civ_border_color="#FF000000"/>
                                        
                                        Glide.load(url)
                                        .centerCrop()
                                        .placeholder(R.drawable.loading_spinner)
                                        .animate(R.anim.fade_in)
                                        .into(YourImageView);
                                        

                                        【讨论】:

                                          猜你喜欢
                                          • 1970-01-01
                                          • 2022-06-10
                                          • 1970-01-01
                                          • 2019-07-02
                                          • 2014-10-26
                                          • 2023-01-12
                                          • 1970-01-01
                                          • 1970-01-01
                                          相关资源
                                          最近更新 更多