0

我有以下自定义可绘制对象,但我需要定义两个 Paint 对象来绘制文本和形状:

public class LetterOvalDrawable
    extends Drawable {

  private final Paint textPaint;
  private final Paint shapePaint;
  private final Rect textRect;
  private String letter;

  public LetterOvalDrawable() {
    textPaint = new Paint();
    shapePaint = new Paint();
    textPaint.setAntiAlias(true);
    shapePaint.setAntiAlias(true);
    textPaint.setTextAlign(Paint.Align.LEFT);
    textRect = new Rect();
  }

  public LetterOvalDrawable(float textSize, @NonNull Typeface typeFace) {
    textPaint = new Paint();
    shapePaint = new Paint();
    textPaint.setAntiAlias(true);
    shapePaint.setAntiAlias(true);
    textPaint.setTextAlign(Paint.Align.LEFT);
    textRect = new Rect();

    textPaint.setTextSize(textSize);
    textPaint.setTypeface(typeFace);
  }

  @Override
  public void draw(@NonNull Canvas canvas) {
    int height = getBounds().height();
    int width = getBounds().width();
    RectF rect = new RectF(0.0f, 0.0f, width, height);
    canvas.drawRoundRect(rect, rect.bottom, rect.right, shapePaint);

    if (letter == null) return;

    textPaint.getTextBounds(letter, 0, letter.length(), textRect);
    float x = width / 2f - textRect.width() / 2f - textRect.left;
    float y = height / 2f + textRect.height() / 2f - textRect.bottom;
    canvas.drawText(letter, x, y, textPaint);
  }

  @Override
  public void setAlpha(int alpha) {
    textPaint.setAlpha(alpha);
    shapePaint.setAlpha(alpha);
  }

  @Override
  public void setColorFilter(@Nullable ColorFilter colorFilter) {
    shapePaint.setColorFilter(colorFilter);
  }

  @Override
  public int getOpacity() {
    return PixelFormat.TRANSLUCENT;
  }

  public void setLetter(String letter) {
    if (letter == null || letter.length() < 1) {
      this.letter = null;
      return;
    }
    if (letter.length() == 1) this.letter = letter.toUpperCase();
    else this.letter = letter.substring(0, 1).toUpperCase();
  }
}

我不喜欢定义两个绘画对象。是否可以重构此代码,以便只有一个 Paint 对象?

或者在android中,是否必须拥有这两个对象?如果这是一个基本问题,请原谅,我是 android 新手,在文档中找不到任何内容。

4

0 回答 0