Текст растягивается на другом экране в моем пользовательском представлении после настройки размера текста в dp android

Я пытаюсь создать текстовую наклейку в android. Я создаю текстовую наклейку на одном из своих телефонов, а затем сохраняю размер текста в DP. Затем на другом телефоне я загружаю тот же текст с тем же DP и конвертирую значение DP в пиксель. Затем вызов метода

TextPaint.setTextSize(pixelValue)

Но вывод на обоих телефонах разный. Я также пробовал заменить DP на SP, но, похоже, это не решение.

Еще одна вещь: я определяю ширину и высоту своего представления на основе высоты ширины (res), которую можно рисовать.

Вот код этого чертежа

      
       <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="@android:color/transparent" />
        <size android:width="200dp" android:height="50dp" />
    </shape>

Но это не похоже на проблему, поскольку значения указаны в DP в файле с возможностью рисования.

Вот конструктор текстовой наклейки.

          public DynamicTextSticker(@NonNull Context context, @Nullable Drawable drawable, String text) {
    this.context = context;
    this.drawable = drawable;
    if (drawable == null) {
      this.drawable = ContextCompat.getDrawable(context, R.drawable.sticker_transparent_background);
    }
    textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    minTextSizePixels = DensityUtils.px2dp(context, 6);
    maxTextSizePixels =  DensityUtils.px2dp(context, 32);
    alignment = Layout.Alignment.ALIGN_CENTER;
    textPaint.setTextSize(maxTextSizePixels);
    realBounds = new Rect(0, 0, getWidth(), getHeight());
    textRect = new Rect(0, 0, getWidth(), getHeight());
  }
      draw method
      @Override public void draw(@NonNull Canvas canvas) {
Matrix matrix = getMatrix();
canvas.save();
canvas.concat(matrix);
if (drawable != null) {
  
  drawable.setBounds(realBounds);
  drawable.draw(canvas);
}
canvas.restore();
canvas.save();
canvas.concat(matrix);
if (textRect.width() == getWidth()) {
  int dy = getHeight() / 2 - staticLayout.getHeight() / 2;
  // center vertical
  canvas.translate(0, dy);
} else {
  int dx = textRect.left;
  int dy = textRect.top + textRect.height() / 2 - staticLayout.getHeight() / 2;
  canvas.translate(dx, dy);
}
staticLayout.draw(canvas);
canvas.restore();

}

      
here is the resize method where the static layout is initialized
      final int availableHeightPixels = textRect.height();

final int availableWidthPixels = textRect.width();

final CharSequence text = getText();

// Safety check
// (Do not resize if the view does not have dimensions or if there is no text)
if (text == null
        || text.length() <= 0
        || availableHeightPixels <= 0
        || availableWidthPixels <= 0
        || maxTextSizePixels <= 0) {
  return this;
}

float targetTextSizePixels = maxTextSizePixels;
int targetTextHeightPixels =
        getTextHeightPixels(text, availableWidthPixels, targetTextSizePixels);

// Until we either fit within our TextView
// or we have reached our minimum text size,
// incrementally try smaller sizes
while (targetTextHeightPixels > availableHeightPixels
        && targetTextSizePixels > minTextSizePixels) {
  targetTextSizePixels = Math.max(targetTextSizePixels - 2, minTextSizePixels);

  targetTextHeightPixels =
          getTextHeightPixels(text, availableWidthPixels, targetTextSizePixels);
}

// If we have reached our minimum text size and the text still doesn't fit,
// append an ellipsis
// (NOTE: Auto-ellipsize doesn't work hence why we have to do it here)
if (targetTextSizePixels == minTextSizePixels
        && targetTextHeightPixels > availableHeightPixels) {
  // Make a copy of the original TextPaint object for measuring
  TextPaint textPaintCopy = new TextPaint(textPaint);
  textPaintCopy.setTextSize(targetTextSizePixels);

  // Measure using a StaticLayout instance
  StaticLayout staticLayout =
          new StaticLayout(text, textPaintCopy, availableWidthPixels, Layout.Alignment.ALIGN_NORMAL,
                  lineSpacingMultiplier, lineSpacingExtra, false);

  // Check that we have a least one line of rendered text
  if (staticLayout.getLineCount() > 0) {
    // Since the line at the specific vertical position would be cut off,
    // we must trim up to the previous line and add an ellipsis
    int lastLine = staticLayout.getLineForVertical(availableHeightPixels) - 1;

    if (lastLine >= 0) {
      int startOffset = staticLayout.getLineStart(lastLine);
      int endOffset = staticLayout.getLineEnd(lastLine);
      float lineWidthPixels = staticLayout.getLineWidth(lastLine);
      float ellipseWidth = textPaintCopy.measureText(mEllipsis);

      // Trim characters off until we have enough room to draw the ellipsis
      while (availableWidthPixels < lineWidthPixels + ellipseWidth) {
        endOffset--;
        lineWidthPixels =
                textPaintCopy.measureText(text.subSequence(startOffset, endOffset + 1).toString());
      }

      setText(text.subSequence(0, endOffset) + mEllipsis);
    }
  }
}
textPaint.setTextSize(targetTextSizePixels);
this.targetTextSizePixel = targetTextSizePixels;
staticLayout =
        new StaticLayout(this.text, textPaint, textRect.width(), alignment, lineSpacingMultiplier,
                lineSpacingExtra, true);
return this;
      
here is the getWidth and getHeight method
          @Override public int getWidth() {
    return drawable.getIntrinsicWidth();
  }

  @Override public int getHeight() {
    return drawable.getIntrinsicHeight();
  }
      I tried several ways but none of them worked for me.

I think the problem is not with text size. but the problem might be with drawable. But I don't know what possibly could go wrong with that, as I have used DP unit everywhere. 
**If i forget to add any code please tell me I will attach it as well**

I am new to android so I am not sure the reason behind this problem.
Thanks for your help.

0 ответов

Другие вопросы по тегам