How to make an ImageView with rounded corners?

前端 未结 30 2490
天涯浪人
天涯浪人 2020-11-21 05:39

In Android, an ImageView is a rectangle by default. How can I make it a rounded rectangle (clip off all 4 corners of my Bitmap to be rounded rectangles) in the ImageView?

30条回答
  •  礼貌的吻别
    2020-11-21 06:27

    As of recently, there is another way - using Glide's Generated API. It takes some initial work but then gives you all the power of Glide with the flexibility to do anything because you writhe the actual code so I think it's a good solution for the long run. Plus, the usage is very simple and neat.

    First, setup Glide version 4+:

    implementation 'com.github.bumptech.glide:glide:4.6.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
    

    Then create Glid's app module class to trigger the annotation processing:

    @GlideModule
    public final class MyAppGlideModule extends AppGlideModule {}
    

    Then create the Glide extension which actually does the work. You can customize it to do whatever you want:

    @GlideExtension
    public class MyGlideExtension {
    
        private MyGlideExtension() {}
    
        @NonNull
        @GlideOption
        public static RequestOptions roundedCorners(RequestOptions options, @NonNull Context context, int cornerRadius) {
            int px = Math.round(cornerRadius * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
            return options.transforms(new RoundedCorners(px));
        }
    }
    

    After adding these files, build your project.

    Then use it in your code like this:

    GlideApp.with(this)
            .load(imageUrl)
            .roundedCorners(getApplicationContext(), 5)
            .into(imageView);
    

提交回复
热议问题