oynix

于无声处听惊雷,于无色处见繁花

CircleImageView

Android 系统默认的 ImageView 是矩形,但有时页面上需要展示圆形的图片,如头像。这里提供一种最简单的实现思路。

将圆形遮罩当作目标(DST),图片当作源(SRC)
先画的是destination,后画的是source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class CircleImageView extends AppCompatImageView {

private Paint mPaint;
private Xfermode mXfermodeDstOut;
private Path mPath;

public CircleImageView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}

private void init() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
mPaint.setStyle(Paint.Style.FILL);
mXfermodeDstOut = new PorterDuffXfermode(PorterDuff.Mode.DST_OUT);
}

@Override
protected void onDraw(Canvas canvas) {
if (mPath == null) {
int w = getWidth();
int h = getHeight();
int cx = w / 2;
int cy = h / 2;
mPath = new Path();
mPath.moveTo(0, 0);
mPath.lineTo(w, 0);
mPath.lineTo(w, h);
mPath.lineTo(0, h);
mPath.addCircle(cx, cy, Math.min(cx, cy), Path.Direction.CCW);
}
canvas.saveLayer(0, 0, getWidth(), getHeight(), mPaint, Canvas.ALL_SAVE_FLAG);
super.onDraw(canvas);
mPaint.setXfermode(mXfermodeDstOut);
canvas.drawPath(mPath, mPaint);
mPaint.setXfermode(null);
canvas.restore();
}
}

源文件

------------- (完) -------------
  • 本文作者: oynix
  • 本文链接: https://oynix.com/2020/02/79bebe7bce6d/
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

欢迎关注我的其它发布渠道