Android實(shí)現(xiàn)圓形圖片效果
本文實(shí)例為大家分享了Android實(shí)現(xiàn)圓形圖片效果的具體代碼,供大家參考,具體內(nèi)容如下
創(chuàng)建RoundPicture.java文件
在src/main/java/XX包下新建RoundPicture.java
寫入RoundPicture.java文件
復(fù)制下方代碼,并引入類即可
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; }}
調(diào)用RoundPicture創(chuàng)建圓形圖片
只需在.xml文件中插入圖片處,將控件名改為< XX.RoundPicture 并引入圖片即可
<com.example.jh_android.RoundPicture android: android:layout_height='200dp' android:layout_width='200dp' android:layout_marginTop='150dp' android:layout_centerHorizontal='true' android:src='http://m.cgvv.com.cn/bcjs/@drawable/head' />
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 推薦一個(gè)好看Table表格的css樣式代碼詳解2. 基于Surprise協(xié)同過濾實(shí)現(xiàn)短視頻推薦方法示例3. 不使用XMLHttpRequest對象實(shí)現(xiàn)Ajax效果的方法小結(jié)4. vue-electron中修改表格內(nèi)容并修改樣式5. 微信小程序?qū)崿F(xiàn)商品分類頁過程結(jié)束6. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式7. ASP新手必備的基礎(chǔ)知識(shí)8. AJAX實(shí)現(xiàn)文件上傳功能報(bào)錯(cuò)Current request is not a multipart request詳解9. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總10. ASP常用日期格式化函數(shù) FormatDate()
