最近做了个UI效果,要求头像是圆形的,外面有白色边框
有需要的同学可以看看,效果如下
附上实现代码
RoundImageView:
public class RoundImageView extends ImageView { public RoundImageView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public RoundImageView(Context context) { super(context); init(); } private final RectF roundRect = new RectF(); private float rect_adius = 90; private final Paint maskPaint = new Paint(); private final Paint zonePaint = new Paint(); private void init() { maskPaint.setAntiAlias(true); maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); maskPaint.setFilterBitmap(true); zonePaint.setAntiAlias(true); zonePaint.setColor(Color.WHITE); zonePaint.setFilterBitmap(true); float density = getResources().getDisplayMetrics().density; rect_adius = rect_adius * density; } public void setRectAdius(float adius) { rect_adius = adius; invalidate(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); int w = getWidth(); int h = getHeight(); roundRect.set(0, 0, w, h); } @Override public void draw(Canvas canvas) { canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG); canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint); // canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG); super.draw(canvas); canvas.restore(); } }
xml文件:
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" android:gravity="center_vertical" > <com.example.view.RoundImageView android:id="@+id/img_user_icon" android:layout_width="100dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:scaleType="centerCrop" android:src="@drawable/user_icon" /> <ImageView android:layout_width="100dp" android:layout_height="100dp" android:layout_centerHorizontal="true" android:background="@drawable/usericon_bg_circle" /> </RelativeLayout>
drawable文件:
usericon_bg_circle.xml
<?xml version="1.0" encoding="UTF-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <solid android:color="#00000000" /> <corners android:radius="90dp" /> <stroke android:width="2dp" android:color="#fff" /> </shape>
时间: 2024-11-12 10:30:24