Java Code Examples for android.text.Layout.Alignment#ALIGN_NORMAL

The following examples show how to use android.text.Layout.Alignment#ALIGN_NORMAL . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebvttCueParser.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
private static Alignment parseTextAlignment(String s) {
  switch (s) {
    case "start":
    case "left":
      return Alignment.ALIGN_NORMAL;
    case "center":
    case "middle":
      return Alignment.ALIGN_CENTER;
    case "end":
    case "right":
      return Alignment.ALIGN_OPPOSITE;
    default:
      Log.w(TAG, "Invalid alignment value: " + s);
      return null;
  }
}
 
Example 2
Source File: WebvttCueParser.java    From K-Sonic with MIT License 6 votes vote down vote up
private static Alignment parseTextAlignment(String s) {
  switch (s) {
    case "start":
    case "left":
      return Alignment.ALIGN_NORMAL;
    case "center":
    case "middle":
      return Alignment.ALIGN_CENTER;
    case "end":
    case "right":
      return Alignment.ALIGN_OPPOSITE;
    default:
      Log.w(TAG, "Invalid alignment value: " + s);
      return null;
  }
}
 
Example 3
Source File: WebvttCueParser.java    From no-player with Apache License 2.0 6 votes vote down vote up
private static Alignment parseTextAlignment(String s) {
    switch (s) {
        case "start":
        case "left":
            return Alignment.ALIGN_NORMAL;
        case "center":
        case "middle":
            return Alignment.ALIGN_CENTER;
        case "end":
        case "right":
            return Alignment.ALIGN_OPPOSITE;
        default:
            Log.w(TAG, "Invalid alignment value: " + s);
            return null;
    }
}
 
Example 4
Source File: WebvttCueParser.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
private static Alignment parseTextAlignment(String s) {
  switch (s) {
    case "start":
    case "left":
      return Alignment.ALIGN_NORMAL;
    case "center":
    case "middle":
      return Alignment.ALIGN_CENTER;
    case "end":
    case "right":
      return Alignment.ALIGN_OPPOSITE;
    default:
      Log.w(TAG, "Invalid alignment value: " + s);
      return null;
  }
}
 
Example 5
Source File: AutoResizingTextView.java    From Simple-Solitaire with GNU General Public License v3.0 5 votes vote down vote up
private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
    // modified: make a copy of the original TextPaint object for measuring
    // (apparently the object gets modified while measuring, see also the
    // docs for TextView.getPaint() (which states to access it read-only)
    TextPaint paintCopy = new TextPaint(paint);
    // Update the text paint object
    paintCopy.setTextSize(textSize);
    // Measure using a static layout
    StaticLayout layout = new StaticLayout(source, paintCopy, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
    return layout.getHeight();
}
 
Example 6
Source File: TableHandler.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@Override public void draw(@NonNull Canvas canvas) {
    Paint paint = new Paint();
    paint.setColor(textColor);
    paint.setStyle(Style.STROKE);

    int numberOfColumns = tableRow.size();

    if (numberOfColumns == 0) {
        return;
    }

    int columnWidth = tableWidth / numberOfColumns;

    int offset;

    for (int i = 0; i < numberOfColumns; i++) {

        offset = i * columnWidth;

        if (paintBorder) {
            // The rect is open at the bottom, so there's a single line
            // between rows.
            canvas.drawRect(offset, 0, offset + columnWidth, rowHeight, paint);
        }

        StaticLayout layout = new StaticLayout(tableRow.get(i),
                getTextPaint(), (columnWidth - 2 * PADDING),
                Alignment.ALIGN_NORMAL, 1.5f, 0.5f, true);

        canvas.translate(offset + PADDING, 0);
        layout.draw(canvas);
        canvas.translate(-1 * (offset + PADDING), 0);

    }
}
 
Example 7
Source File: StaticLayoutBuilderCompat.java    From material-components-android with Apache License 2.0 5 votes vote down vote up
private StaticLayoutBuilderCompat(CharSequence source, TextPaint paint, int width) {
  this.source = source;
  this.paint = paint;
  this.width = width;
  this.start = 0;
  this.end = source.length();
  this.alignment = Alignment.ALIGN_NORMAL;
  this.maxLines = Integer.MAX_VALUE;
  this.includePad = true;
  this.ellipsize = null;
}
 
Example 8
Source File: LyricView.java    From RhymeMusic with Apache License 2.0 5 votes vote down vote up
/**
 * 绘制文本,可自动换行
 * @param text
 * @param canvas
 * @param y
 */
private void drawText(String text, Canvas canvas, float y)
{
    int status = canvas.save();
    canvas.translate(mWidth / 2, y);
    int w = mWidth - getPaddingLeft() - getPaddingRight();
    StaticLayout layout = new StaticLayout(text, mPaint, w,
            Alignment.ALIGN_NORMAL, 1.0f, 0, false);
    layout.draw(canvas);
    canvas.restoreToCount(status);
}
 
Example 9
Source File: Cea708Decoder.java    From Telegram-FOSS with GNU General Public License v2.0 4 votes vote down vote up
public Cea708Cue build() {
  if (isEmpty()) {
    // The cue is empty.
    return null;
  }

  SpannableStringBuilder cueString = new SpannableStringBuilder();

  // Add any rolled up captions, separated by new lines.
  for (int i = 0; i < rolledUpCaptions.size(); i++) {
    cueString.append(rolledUpCaptions.get(i));
    cueString.append('\n');
  }
  // Add the current line.
  cueString.append(buildSpannableString());

  // TODO: Add support for right-to-left languages (i.e. where right would correspond to normal
  // alignment).
  Alignment alignment;
  switch (justification) {
    case JUSTIFICATION_FULL:
      // TODO: Add support for full justification.
    case JUSTIFICATION_LEFT:
      alignment = Alignment.ALIGN_NORMAL;
      break;
    case JUSTIFICATION_RIGHT:
      alignment = Alignment.ALIGN_OPPOSITE;
      break;
    case JUSTIFICATION_CENTER:
      alignment = Alignment.ALIGN_CENTER;
      break;
    default:
      throw new IllegalArgumentException("Unexpected justification value: " + justification);
  }

  float position;
  float line;
  if (relativePositioning) {
    position = (float) horizontalAnchor / RELATIVE_CUE_SIZE;
    line = (float) verticalAnchor / RELATIVE_CUE_SIZE;
  } else {
    position = (float) horizontalAnchor / HORIZONTAL_SIZE;
    line = (float) verticalAnchor / VERTICAL_SIZE;
  }
  // Apply screen-edge padding to the line and position.
  position = (position * 0.9f) + 0.05f;
  line = (line * 0.9f) + 0.05f;

  // anchorId specifies where the anchor should be placed on the caption cue/window. The 9
  // possible configurations are as follows:
  //   0-----1-----2
  //   |           |
  //   3     4     5
  //   |           |
  //   6-----7-----8
  @AnchorType int verticalAnchorType;
  if (anchorId % 3 == 0) {
    verticalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId % 3 == 1) {
    verticalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    verticalAnchorType = Cue.ANCHOR_TYPE_END;
  }
  // TODO: Add support for right-to-left languages (i.e. where start is on the right).
  @AnchorType int horizontalAnchorType;
  if (anchorId / 3 == 0) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId / 3 == 1) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    horizontalAnchorType = Cue.ANCHOR_TYPE_END;
  }

  boolean windowColorSet = (windowFillColor != COLOR_SOLID_BLACK);

  return new Cea708Cue(cueString, alignment, line, Cue.LINE_TYPE_FRACTION, verticalAnchorType,
      position, horizontalAnchorType, Cue.DIMEN_UNSET, windowColorSet, windowFillColor,
      priority);
}
 
Example 10
Source File: Cea708Decoder.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
public Cea708Cue build() {
  if (isEmpty()) {
    // The cue is empty.
    return null;
  }

  SpannableStringBuilder cueString = new SpannableStringBuilder();

  // Add any rolled up captions, separated by new lines.
  for (int i = 0; i < rolledUpCaptions.size(); i++) {
    cueString.append(rolledUpCaptions.get(i));
    cueString.append('\n');
  }
  // Add the current line.
  cueString.append(buildSpannableString());

  // TODO: Add support for right-to-left languages (i.e. where right would correspond to normal
  // alignment).
  Alignment alignment;
  switch (justification) {
    case JUSTIFICATION_FULL:
      // TODO: Add support for full justification.
    case JUSTIFICATION_LEFT:
      alignment = Alignment.ALIGN_NORMAL;
      break;
    case JUSTIFICATION_RIGHT:
      alignment = Alignment.ALIGN_OPPOSITE;
      break;
    case JUSTIFICATION_CENTER:
      alignment = Alignment.ALIGN_CENTER;
      break;
    default:
      throw new IllegalArgumentException("Unexpected justification value: " + justification);
  }

  float position;
  float line;
  if (relativePositioning) {
    position = (float) horizontalAnchor / RELATIVE_CUE_SIZE;
    line = (float) verticalAnchor / RELATIVE_CUE_SIZE;
  } else {
    position = (float) horizontalAnchor / HORIZONTAL_SIZE;
    line = (float) verticalAnchor / VERTICAL_SIZE;
  }
  // Apply screen-edge padding to the line and position.
  position = (position * 0.9f) + 0.05f;
  line = (line * 0.9f) + 0.05f;

  // anchorId specifies where the anchor should be placed on the caption cue/window. The 9
  // possible configurations are as follows:
  //   0-----1-----2
  //   |           |
  //   3     4     5
  //   |           |
  //   6-----7-----8
  @AnchorType int verticalAnchorType;
  if (anchorId % 3 == 0) {
    verticalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId % 3 == 1) {
    verticalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    verticalAnchorType = Cue.ANCHOR_TYPE_END;
  }
  // TODO: Add support for right-to-left languages (i.e. where start is on the right).
  @AnchorType int horizontalAnchorType;
  if (anchorId / 3 == 0) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId / 3 == 1) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    horizontalAnchorType = Cue.ANCHOR_TYPE_END;
  }

  boolean windowColorSet = (windowFillColor != COLOR_SOLID_BLACK);

  return new Cea708Cue(cueString, alignment, line, Cue.LINE_TYPE_FRACTION, verticalAnchorType,
      position, horizontalAnchorType, Cue.DIMEN_UNSET, windowColorSet, windowFillColor,
      priority);
}
 
Example 11
Source File: AutoFitTextView.java    From android_gisapp with GNU General Public License v3.0 4 votes vote down vote up
public AutoFitTextView(final Context context,final AttributeSet attrs,final int defStyle)
{
    super(context,attrs,defStyle);
    // using the minimal recommended font size
    _minTextSize=TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,12,getResources().getDisplayMetrics());
    _maxTextSize=getTextSize();
    if(_maxLines==0)
        // no value was assigned during construction
        _maxLines=NO_LINE_LIMIT;
    // prepare size tester:
    _sizeTester=new SizeTester()
    {
        final RectF textRect=new RectF();

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public int onTestSize(final int suggestedSize,final RectF availableSPace)
        {
            paint.setTextSize(suggestedSize);
            final String text=getText().toString();
            final boolean singleLine=getMaxLines()==1;
            if(singleLine)
            {
                textRect.bottom=paint.getFontSpacing();
                textRect.right=paint.measureText(text);
            }
            else
            {
                final StaticLayout layout=new StaticLayout(text,paint,_widthLimit,Alignment.ALIGN_NORMAL,_spacingMult,_spacingAdd,true);
                // return early if we have more lines
                if(getMaxLines()!=NO_LINE_LIMIT&&layout.getLineCount()>getMaxLines())
                    return 1;
                textRect.bottom=layout.getHeight();
                int maxWidth=-1;
                for(int i=0;i<layout.getLineCount();i++)
                    if(maxWidth<layout.getLineRight(i)-layout.getLineLeft(i))
                        maxWidth=(int)layout.getLineRight(i)-(int)layout.getLineLeft(i);
                textRect.right=maxWidth;
            }
            textRect.offsetTo(0,0);
            if(availableSPace.contains(textRect))
                // may be too small, don't worry we will find the best match
                return -1;
            // else, too big
            return 1;
        }
    };
    _initiallized=true;
}
 
Example 12
Source File: Cea608Decoder.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
public Cue build() {
  SpannableStringBuilder cueString = new SpannableStringBuilder();
  // Add any rolled up captions, separated by new lines.
  for (int i = 0; i < rolledUpCaptions.size(); i++) {
    cueString.append(rolledUpCaptions.get(i));
    cueString.append('\n');
  }
  // Add the current line.
  cueString.append(buildSpannableString());

  if (cueString.length() == 0) {
    // The cue is empty.
    return null;
  }

  float position;
  int positionAnchor;
  // The number of empty columns before the start of the text, in the range [0-31].
  int startPadding = indent + tabOffset;
  // The number of empty columns after the end of the text, in the same range.
  int endPadding = SCREEN_CHARWIDTH - startPadding - cueString.length();
  int startEndPaddingDelta = startPadding - endPadding;
  if (captionMode == CC_MODE_POP_ON && (Math.abs(startEndPaddingDelta) < 3 || endPadding < 0)) {
    // Treat approximately centered pop-on captions as middle aligned. We also treat captions
    // that are wider than they should be in this way. See
    // https://github.com/google/ExoPlayer/issues/3534.
    position = 0.5f;
    positionAnchor = Cue.ANCHOR_TYPE_MIDDLE;
  } else if (captionMode == CC_MODE_POP_ON && startEndPaddingDelta > 0) {
    // Treat pop-on captions with less padding at the end than the start as end aligned.
    position = (float) (SCREEN_CHARWIDTH - endPadding) / SCREEN_CHARWIDTH;
    // Adjust the position to fit within the safe area.
    position = position * 0.8f + 0.1f;
    positionAnchor = Cue.ANCHOR_TYPE_END;
  } else {
    // For all other cases assume start aligned.
    position = (float) startPadding / SCREEN_CHARWIDTH;
    // Adjust the position to fit within the safe area.
    position = position * 0.8f + 0.1f;
    positionAnchor = Cue.ANCHOR_TYPE_START;
  }

  int lineAnchor;
  int line;
  // Note: Row indices are in the range [1-15].
  if (captionMode == CC_MODE_ROLL_UP || row > (BASE_ROW / 2)) {
    lineAnchor = Cue.ANCHOR_TYPE_END;
    line = row - BASE_ROW;
    // Two line adjustments. The first is because line indices from the bottom of the window
    // start from -1 rather than 0. The second is a blank row to act as the safe area.
    line -= 2;
  } else {
    lineAnchor = Cue.ANCHOR_TYPE_START;
    // Line indices from the top of the window start from 0, but we want a blank row to act as
    // the safe area. As a result no adjustment is necessary.
    line = row;
  }

  return new Cue(cueString, Alignment.ALIGN_NORMAL, line, Cue.LINE_TYPE_NUMBER, lineAnchor,
      position, positionAnchor, Cue.DIMEN_UNSET);
}
 
Example 13
Source File: Cea708Decoder.java    From TelePlus-Android with GNU General Public License v2.0 4 votes vote down vote up
public Cea708Cue build() {
  if (isEmpty()) {
    // The cue is empty.
    return null;
  }

  SpannableStringBuilder cueString = new SpannableStringBuilder();

  // Add any rolled up captions, separated by new lines.
  for (int i = 0; i < rolledUpCaptions.size(); i++) {
    cueString.append(rolledUpCaptions.get(i));
    cueString.append('\n');
  }
  // Add the current line.
  cueString.append(buildSpannableString());

  // TODO: Add support for right-to-left languages (i.e. where right would correspond to normal
  // alignment).
  Alignment alignment;
  switch (justification) {
    case JUSTIFICATION_FULL:
      // TODO: Add support for full justification.
    case JUSTIFICATION_LEFT:
      alignment = Alignment.ALIGN_NORMAL;
      break;
    case JUSTIFICATION_RIGHT:
      alignment = Alignment.ALIGN_OPPOSITE;
      break;
    case JUSTIFICATION_CENTER:
      alignment = Alignment.ALIGN_CENTER;
      break;
    default:
      throw new IllegalArgumentException("Unexpected justification value: " + justification);
  }

  float position;
  float line;
  if (relativePositioning) {
    position = (float) horizontalAnchor / RELATIVE_CUE_SIZE;
    line = (float) verticalAnchor / RELATIVE_CUE_SIZE;
  } else {
    position = (float) horizontalAnchor / HORIZONTAL_SIZE;
    line = (float) verticalAnchor / VERTICAL_SIZE;
  }
  // Apply screen-edge padding to the line and position.
  position = (position * 0.9f) + 0.05f;
  line = (line * 0.9f) + 0.05f;

  // anchorId specifies where the anchor should be placed on the caption cue/window. The 9
  // possible configurations are as follows:
  //   0-----1-----2
  //   |           |
  //   3     4     5
  //   |           |
  //   6-----7-----8
  @AnchorType int verticalAnchorType;
  if (anchorId % 3 == 0) {
    verticalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId % 3 == 1) {
    verticalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    verticalAnchorType = Cue.ANCHOR_TYPE_END;
  }
  // TODO: Add support for right-to-left languages (i.e. where start is on the right).
  @AnchorType int horizontalAnchorType;
  if (anchorId / 3 == 0) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_START;
  } else if (anchorId / 3 == 1) {
    horizontalAnchorType = Cue.ANCHOR_TYPE_MIDDLE;
  } else {
    horizontalAnchorType = Cue.ANCHOR_TYPE_END;
  }

  boolean windowColorSet = (windowFillColor != COLOR_SOLID_BLACK);

  return new Cea708Cue(cueString, alignment, line, Cue.LINE_TYPE_FRACTION, verticalAnchorType,
      position, horizontalAnchorType, Cue.DIMEN_UNSET, windowColorSet, windowFillColor,
      priority);
}
 
Example 14
Source File: SizeAdjustingTextView.java    From MaterialCalendar with Apache License 2.0 4 votes vote down vote up
private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
    paint.setTextSize(textSize);
    StaticLayout layout = new StaticLayout(source, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
    return layout.getHeight();
}
 
Example 15
Source File: TableHandler.java    From SDHtmlTextView with Apache License 2.0 4 votes vote down vote up
private int calculateRowHeight(List<Spanned> row) {

		if (row.size() == 0) {
			return 0;
		}

		TextPaint textPaint = getTextPaint();

		int columnWidth = tableWidth / row.size();

		int rowHeight = 0;

		for (Spanned cell : row) {

			StaticLayout layout = new StaticLayout(cell, textPaint, columnWidth
					- 2 * PADDING, Alignment.ALIGN_NORMAL, 1f, 0f, true);

			if (layout.getHeight() > rowHeight) {
				rowHeight = layout.getHeight();
			}
		}

		return rowHeight;
	}
 
Example 16
Source File: AutoResizeTextView.java    From android with Apache License 2.0 4 votes vote down vote up
public AutoResizeTextView(final Context context, final AttributeSet attrs, final int defStyle) {
    super(context, attrs, defStyle);
    // using the minimal recommended font size
    minTextSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics());
    maxTextSize = getTextSize();
    if (maxLines == 0)
        // no value was assigned during construction
        maxLines = NO_LINE_LIMIT;
    // prepare size tester:
    sizeTester = new SizeTester() {
        final RectF textRect = new RectF();

        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        @Override
        public int onTestSize(final int suggestedSize, final RectF availableSPace) {
            if (paint == null)
                paint = new TextPaint(getPaint());
            paint.setTextSize(suggestedSize);

            final String text = getText().toString();
            final boolean singleline = getMaxLines() == 1;
            if (singleline) {
                textRect.bottom = paint.getFontSpacing();
                textRect.right = paint.measureText(text);
            } else {
                final StaticLayout layout = new StaticLayout(text, paint, widthLimit, Alignment.ALIGN_NORMAL, spacingMult, spacingAdd, true);
                // return early if we have more lines
                if (getMaxLines() != NO_LINE_LIMIT && layout.getLineCount() > getMaxLines())
                    return 1;
                textRect.bottom = layout.getHeight();
                int maxWidth = -1;
                for (int i = 0; i < layout.getLineCount(); i++)
                    if (maxWidth < layout.getLineRight(i) - layout.getLineLeft(i))
                        maxWidth = (int) layout.getLineRight(i) - (int) layout.getLineLeft(i);
                textRect.right = maxWidth;
            }
            textRect.offsetTo(0, 0);
            if (availableSPace.contains(textRect))
                // may be too small, don't worry we will find the best match
                return -1;
            // else, too big
            return 1;
        }
    };
    initiallized = true;
}
 
Example 17
Source File: Cea608Decoder.java    From MediaSDK with Apache License 2.0 4 votes vote down vote up
public Cue build(@Cue.AnchorType int forcedPositionAnchor) {
  SpannableStringBuilder cueString = new SpannableStringBuilder();
  // Add any rolled up captions, separated by new lines.
  for (int i = 0; i < rolledUpCaptions.size(); i++) {
    cueString.append(rolledUpCaptions.get(i));
    cueString.append('\n');
  }
  // Add the current line.
  cueString.append(buildCurrentLine());

  if (cueString.length() == 0) {
    // The cue is empty.
    return null;
  }

  int positionAnchor;
  // The number of empty columns before the start of the text, in the range [0-31].
  int startPadding = indent + tabOffset;
  // The number of empty columns after the end of the text, in the same range.
  int endPadding = SCREEN_CHARWIDTH - startPadding - cueString.length();
  int startEndPaddingDelta = startPadding - endPadding;
  if (forcedPositionAnchor != Cue.TYPE_UNSET) {
    positionAnchor = forcedPositionAnchor;
  } else if (captionMode == CC_MODE_POP_ON
      && (Math.abs(startEndPaddingDelta) < 3 || endPadding < 0)) {
    // Treat approximately centered pop-on captions as middle aligned. We also treat captions
    // that are wider than they should be in this way. See
    // https://github.com/google/ExoPlayer/issues/3534.
    positionAnchor = Cue.ANCHOR_TYPE_MIDDLE;
  } else if (captionMode == CC_MODE_POP_ON && startEndPaddingDelta > 0) {
    // Treat pop-on captions with less padding at the end than the start as end aligned.
    positionAnchor = Cue.ANCHOR_TYPE_END;
  } else {
    // For all other cases assume start aligned.
    positionAnchor = Cue.ANCHOR_TYPE_START;
  }

  float position;
  switch (positionAnchor) {
    case Cue.ANCHOR_TYPE_MIDDLE:
      position = 0.5f;
      break;
    case Cue.ANCHOR_TYPE_END:
      position = (float) (SCREEN_CHARWIDTH - endPadding) / SCREEN_CHARWIDTH;
      // Adjust the position to fit within the safe area.
      position = position * 0.8f + 0.1f;
      break;
    case Cue.ANCHOR_TYPE_START:
    default:
      position = (float) startPadding / SCREEN_CHARWIDTH;
      // Adjust the position to fit within the safe area.
      position = position * 0.8f + 0.1f;
      break;
  }

  int lineAnchor;
  int line;
  // Note: Row indices are in the range [1-15].
  if (captionMode == CC_MODE_ROLL_UP || row > (BASE_ROW / 2)) {
    lineAnchor = Cue.ANCHOR_TYPE_END;
    line = row - BASE_ROW;
    // Two line adjustments. The first is because line indices from the bottom of the window
    // start from -1 rather than 0. The second is a blank row to act as the safe area.
    line -= 2;
  } else {
    lineAnchor = Cue.ANCHOR_TYPE_START;
    // Line indices from the top of the window start from 0, but we want a blank row to act as
    // the safe area. As a result no adjustment is necessary.
    line = row;
  }

  return new Cue(
      cueString,
      Alignment.ALIGN_NORMAL,
      line,
      Cue.LINE_TYPE_NUMBER,
      lineAnchor,
      position,
      positionAnchor,
      Cue.DIMEN_UNSET);
}
 
Example 18
Source File: SizeAdjustingTextView.java    From SizeAdjustingTextView with GNU General Public License v2.0 4 votes vote down vote up
private int getTextHeight(CharSequence source, TextPaint paint, int width, float textSize) {
    paint.setTextSize(textSize);
    StaticLayout layout = new StaticLayout(source, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
    return layout.getHeight();
}
 
Example 19
Source File: AutoResizeTextView.java    From oneHookLibraryAndroid with Apache License 2.0 4 votes vote down vote up
/**
 * Resize the text size with specified width and height
 * @param width
 * @param height
 */
public void resizeText(int width, int height) {
    CharSequence text = getText();
    // Do not resize if the view does not have dimensions or there is no text
    if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
        return;
    }

    if (getTransformationMethod() != null) {
        text = getTransformationMethod().getTransformation(text, this);
    }

    // Get the text view's paint object
    TextPaint textPaint = getPaint();

    // Store the current text size
    float oldTextSize = textPaint.getTextSize();
    // If there is a max text size set, use the lesser of that and the default text size
    float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

    // Get the required text height
    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

    // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
    while (textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }

    // If we had reached our minimum text size and still don't fit, append an ellipsis
    if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
        // Draw using a static layout
        // modified: use a copy of TextPaint for measuring
        TextPaint paint = new TextPaint(textPaint);
        // Draw using a static layout
        StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
        // Check that we have a least one line of rendered text
        if (layout.getLineCount() > 0) {
            // Since the line at the specific vertical position would be cut off,
            // we must trim up to the previous line
            int lastLine = layout.getLineForVertical(height) - 1;
            // If the text would not even fit on a single line, clear it
            if (lastLine < 0) {
                setText("");
            }
            // Otherwise, trim to the previous line and add an ellipsis
            else {
                int start = layout.getLineStart(lastLine);
                int end = layout.getLineEnd(lastLine);
                float lineWidth = layout.getLineWidth(lastLine);
                float ellipseWidth = textPaint.measureText(mEllipsis);

                // Trim characters off until we have enough room to draw the ellipsis
                while (width < lineWidth + ellipseWidth) {
                    lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
                }
                setText(text.subSequence(0, end) + mEllipsis);
            }
        }
    }

    // Some devices try to auto adjust line spacing, so force default line spacing
    // and invalidate the layout as a side effect
    setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

    // Notify the listener if registered
    if (mTextResizeListener != null) {
        mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
    }

    // Reset force resize flag
    mNeedsResize = false;
}
 
Example 20
Source File: AutoResizingTextView.java    From Simple-Solitaire with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Resize the text size with specified width and height
 *
 * @param width
 * @param height
 */
public void resizeText(int width, int height) {
    CharSequence text = getText();
    // Do not resize if the view does not have dimensions or there is no text
    if (text == null || text.length() == 0 || height <= 0 || width <= 0 || mTextSize == 0) {
        return;
    }

    if (getTransformationMethod() != null) {
        text = getTransformationMethod().getTransformation(text, this);
    }

    // Get the text view's paint object
    TextPaint textPaint = getPaint();

    // Store the current text size
    float oldTextSize = textPaint.getTextSize();
    // If there is a max text size set, use the lesser of that and the default text size
    float targetTextSize = mMaxTextSize > 0 ? Math.min(mTextSize, mMaxTextSize) : mTextSize;

    // Get the required text height
    int textHeight = getTextHeight(text, textPaint, width, targetTextSize);

    // Until we either fit within our text view or we had reached our min text size, incrementally try smaller sizes
    while (textHeight > height && targetTextSize > mMinTextSize) {
        targetTextSize = Math.max(targetTextSize - 2, mMinTextSize);
        textHeight = getTextHeight(text, textPaint, width, targetTextSize);
    }

    // If we had reached our minimum text size and still don't fit, append an ellipsis
    if (mAddEllipsis && targetTextSize == mMinTextSize && textHeight > height) {
        // Draw using a static layout
        // modified: use a copy of TextPaint for measuring
        TextPaint paint = new TextPaint(textPaint);
        // Draw using a static layout
        StaticLayout layout = new StaticLayout(text, paint, width, Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, false);
        // Check that we have a least one line of rendered text
        if (layout.getLineCount() > 0) {
            // Since the line at the specific vertical position would be cut off,
            // we must trim up to the previous line
            int lastLine = layout.getLineForVertical(height) - 1;
            // If the text would not even fit on a single line, clear it
            if (lastLine < 0) {
                setText("");
            }
            // Otherwise, trim to the previous line and add an ellipsis
            else {
                int start = layout.getLineStart(lastLine);
                int end = layout.getLineEnd(lastLine);
                float lineWidth = layout.getLineWidth(lastLine);
                float ellipseWidth = textPaint.measureText(mEllipsis);

                // Trim characters off until we have enough room to draw the ellipsis
                while (width < lineWidth + ellipseWidth) {
                    lineWidth = textPaint.measureText(text.subSequence(start, --end + 1).toString());
                }
                setText(text.subSequence(0, end) + mEllipsis);
            }
        }
    }

    // Some devices try to auto adjust line spacing, so force default line spacing
    // and invalidate the layout as a side effect
    setTextSize(TypedValue.COMPLEX_UNIT_PX, targetTextSize);
    setLineSpacing(mSpacingAdd, mSpacingMult);

    // Notify the listener if registered
    if (mTextResizeListener != null) {
        mTextResizeListener.onTextResize(this, oldTextSize, targetTextSize);
    }

    // Reset force resize flag
    mNeedsResize = false;
}