Android 设置图片为圆角或者圆形

亦凉 2022-10-15 11:59 120阅读 0赞

自己写了一个工具类,使用自定义view,设置图片为圆角,当rect_adius=100时,圆角就会变成圆形

  1. public class RoundImageView extends AppCompatImageView {
  2. private final RectF roundRect = new RectF();
  3. private float rect_adius = 10;
  4. private final Paint maskPaint = new Paint();
  5. private final Paint zonePaint = new Paint();
  6. public RoundImageView(Context context, AttributeSet attrs) {
  7. super(context, attrs);
  8. TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
  9. //根据属性名称获取对应的值,属性名称的格式为类名_属性名
  10. rect_adius = typedArray.getFloat(R.styleable.RoundImageView_rect_adius, 10f);
  11. init();
  12. }
  13. public RoundImageView(Context context) {
  14. super(context);
  15. init();
  16. }
  17. private void init() {
  18. maskPaint.setAntiAlias(true);
  19. maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
  20. zonePaint.setAntiAlias(true);
  21. zonePaint.setColor(Color.WHITE);
  22. float density = getResources().getDisplayMetrics().density;
  23. rect_adius = rect_adius * density;
  24. }
  25. public void setRectAdius(float adius) {
  26. rect_adius = adius;
  27. invalidate();
  28. }
  29. @Override
  30. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
  31. super.onLayout(changed, left, top, right, bottom);
  32. int w = getWidth();
  33. int h = getHeight();
  34. roundRect.set(0, 0, w, h);
  35. }
  36. @Override
  37. public void draw(Canvas canvas) {
  38. canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
  39. canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
  40. canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
  41. super.draw(canvas);
  42. canvas.restore();
  43. }
  44. }

在styles中添加

  1. <declare-styleable name="RoundImageView">
  2. <attr name="rect_adius" format="float" />
  3. </declare-styleable>

发表评论

表情:
评论列表 (有 0 条评论,120人围观)

还没有评论,来说两句吧...

相关阅读