I have 1 circular imageview and I want to place bitmap inside the imageview. but when I set the compressed bitmap image it is always rectangle. Please help me to set bitmap in circular imageview开发者_运维技巧.
Thanks
I am curious about how you created a circular ImageView. Can you share that secret ?? As far as creating a circular Bitmap is concerned, create a BitmapShader from the bitmap you want to show. Then create a ShapeDrawable (Oval) and assign the bitmap shader to it. Draw the drawable. Bam! circular image!
Bitmap bitmap = getthebitmapyouwanttoshowinacirclefromsomewhere;
Bitmap circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader (bitmap, TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getWidth()/2, paint);
myImageView.setImageBitmap(circleBitmap);
Androidx released native support for this.
add to your build.gradle
:
dependencies {
...
implementation "androidx.core:core-ktx:1.7.0"
}
usage (kotlin is shown here, java is also supported):
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
val bitmap: Bitmap = ... // get from somewhere
val roundedBitmapWrapper: RoundedBitmapDrawable =
RoundedBitmapDrawableFactory.create(Resources.getSystem(), bitmap)
roundedBitmapWrapper.setCircular(true) // important! if you don't call this, the wrapper will just show the original rectangle bitmap
// and then you can display the roundedBitmap on an ImageView like this:
val imageView: ImageView = ... // get from somewhere
imageView.setImageDrawable(roundedBitmapWrapper)
P.S., the class RoundedBitmapDrawable
has a lot of other cool stuff, for example if you don't want the bitmap to be completely circle, but instead just give some rounded-corners effect for the original rectangle bitmap, this can also be supported. check out the official doc at https://developer.android.com/reference/androidx/core/graphics/drawable/RoundedBitmapDrawable
精彩评论