本篇文章為大家展示了Android中怎么實現圓形圖片效果,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
創建RoundPicture.java文件
在src/main/java/XX包下新建RoundPicture.java


寫入RoundPicture.java文件
復制下方代碼,并引入類即可
public class RoundPicture extends androidx.appcompat.widget.AppCompatImageView {
private Paint paint;
public RoundPicture(Context context) {
this(context, null);
}
public RoundPicture(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundPicture(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
}
// 繪制圓形圖片
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (null != drawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
Bitmap b = getCircleBitmap(bitmap, 14);
final Rect rectSrc = new Rect(0, 0, b.getWidth(), b.getHeight());
final Rect rectDest = new Rect(0, 0, getWidth(), getHeight());
paint.reset();
canvas.drawBitmap(b, rectSrc, rectDest, paint);
} else {
super.onDraw(canvas);
}
}
// 獲取圓形圖片方法
private Bitmap getCircleBitmap(Bitmap bitmap, int pixels) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
int x = bitmap.getWidth();
canvas.drawCircle(x / 2, x / 2, x / 2, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
}調用RoundPicture創建圓形圖片
只需在.xml文件中插入圖片處,將控件名改為
< XX.RoundPicture 并引入圖片即可
<com.example.jh_android.RoundPicture android:id="@+id/iv" android:layout_height="200dp" android:layout_width="200dp" android:layout_marginTop="150dp" android:layout_centerHorizontal="true" android:src="@drawable/head" />
上述內容就是Android中怎么實現圓形圖片效果,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。