CircleImageView implements round picture loading skills sharing
CircleImageView is a commonly used custom ImageView, which can display the picture as a round.In Android development, loading round pictures is a common demand.This article will share several techniques to loading round pictures and provide examples of Java code.
1. Use CircleImageView Library
To load round pictures, you can use some open source libraries, such as CircleImageView.First, you need to add the CircleImageView library to the project of the project.Add the following dependencies to the APP's Build. Gradle file:
implementation 'de.hdodenhof:circleimageview:3.1.0'
Then, the ImageView is replaced with the IMAGEVIEW to CircleImageView:
<de.hdodenhof.circleimageview.CircleImageView
android:id="@+id/profile_image"
android:layout_width="120dp"
android:layout_height="120dp"
android:src="@drawable/profile_picture"
app:civ_border_width="2dp"
app:civ_border_color="#FF000000"/>
In the Java code, you can use the CircleImageView to load the circular picture:
CircleImageView profileImage = findViewById(R.id.profile_image);
profileImage.setImageResource(R.drawable.profile_picture);
2. Realize circular pictures by tailoring
If you do not want to use a third -party library, you can also load round pictures by cutting.The following is a simple implementation example:
ImageView profileImage = findViewById(R.id.profile_image);
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.profile_picture);
Bitmap roundBitmap = getCircularBitmap(originalBitmap);
profileImage.setImageBitmap(roundBitmap);
// Cut into round pictures
private Bitmap getCircularBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int radius = Math.min(width, height) / 2;
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Paint paint = new Paint();
Rect rect = new Rect(0, 0, width, height);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawCircle(width / 2, height / 2, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
In the above examples, by calling the `GetcircularBitMap` method, the original picture is cut into a circular shape, and the cut -cut picture is set to ImageView.
Summarize:
This article introduces two techniques to loading circular pictures. One is to use the CircleImageView library, and the other is to achieve circular pictures by cutting.The specific method depends on the needs and preferences of personal projects.Hope the above content will help you!