Java Code Examples for android.text.StaticLayout

The following are top voted examples for showing how to use android.text.StaticLayout. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Demos   File: CustomTextView.java   Source Code and License 11 votes vote down vote up
/**
 * 绘制多行居中文本(方式1)
 *
 * @param canvas 画布
 */
private void drawCenterMultiText1(Canvas canvas) {
    String text = "ABC";

    // 画笔
    TextPaint textPaint = new TextPaint();
    textPaint.setAntiAlias(true);
    textPaint.setColor(Color.GRAY);

    // 设置宽度超过50dp时换行
    StaticLayout staticLayout = new StaticLayout(text, textPaint, dp2px(50),
            Layout.Alignment.ALIGN_CENTER, 1, 0, false);
    canvas.save();
    // StaticLayout默认从(0,0)点开始绘制
    // 如果需要调整位置,只能在绘制之前移动Canvas的起始坐标
    canvas.translate(-staticLayout.getWidth() / 2, -staticLayout.getHeight() / 2);
    staticLayout.draw(canvas);
    canvas.restore();
}
 
Example 2
Project: reflow-animator   File: ReflowTextAnimatorHelper.java   Source Code and License 7 votes vote down vote up
private static Layout createUnrestrictedLayout(@Nonnull TextView view) {
    CharSequence text = view.getText();
    Layout layout = view.getLayout();
    TextPaint paint = layout.getPaint();

    if (SDK_INT >= M) {
        return StaticLayout.Builder
                .obtain(text, 0, text.length(), layout.getPaint(), layout.getWidth())
                .setAlignment(layout.getAlignment())
                .setLineSpacing(view.getLineSpacingExtra(), view.getLineSpacingMultiplier())
                .setIncludePad(view.getIncludeFontPadding())
                .setBreakStrategy(view.getBreakStrategy())
                .setHyphenationFrequency(view.getHyphenationFrequency())
                .build();
    } else {
        return new StaticLayout(
                text,
                paint,
                text.length(),
                layout.getAlignment(),
                view.getLineSpacingMultiplier(),
                view.getLineSpacingExtra(),
                view.getIncludeFontPadding());
    }
}
 
Example 3
Project: GitHub   File: MaterialAutoCompleteTextView.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
      Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
      Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 4
Project: GitHub   File: MaterialEditText.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
        Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
        Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 5
Project: GitHub   File: DanmakuItem.java   Source Code and License 6 votes vote down vote up
private void measure() {
        TextPaint tp = new TextPaint();
        tp.setAntiAlias(true);
        tp.setColor(mTextColor);
        tp.setTextSize(mTextSize);
        strokePaint.setTextSize(mTextSize);
//        tp.setShadowLayer(4, 0, 0, Color.BLACK);
        mContentHeight = getFontHeight(tp);
        staticLayout = new StaticLayout(mContent,
                            tp,
                            (int) Layout.getDesiredWidth(mContent, 0, mContent.length(), tp) + 1,
                            Layout.Alignment.ALIGN_NORMAL,
                            1.0f,
                            0.0f,
                            false);
        mContentWidth = staticLayout.getWidth();
        borderStaticLayout = new StaticLayout(mContent,
                strokePaint,
                (int) Layout.getDesiredWidth(mContent, 0, mContent.length(), tp) + 1,
                Layout.Alignment.ALIGN_NORMAL,
                1.0f,
                0.0f,
                false);
    }
 
Example 6
Project: empty-state-recyclerview   File: TextStateDisplay.java   Source Code and License 6 votes vote down vote up
private float getDx(final int width,
                    final int horizontalGravity,
                    final Paint paint,
                    final StaticLayout layout) {
    final boolean centered = paint.getTextAlign() == Paint.Align.CENTER;
    final float dx;
    switch (horizontalGravity) { // No support for GravityCompat.END
        case Gravity.CENTER_HORIZONTAL:
            dx = (width >> 1) - (centered ? 0 : (layout.getWidth() >> 1) - getPaddingLeft());
            break;
        default:
        case GravityCompat.START:
            dx = getPaddingLeft();
            break;
    }
    return dx;
}
 
Example 7
Project: empty-state-recyclerview   File: TextStateDisplay.java   Source Code and License 6 votes vote down vote up
private void configureTextLayouts(final int availableWidth) {
    if (!textLayoutsConfigured) {
        final int totalNeededPadding = getPaddingLeft() + getPaddingRight();

        // Create new static layout only if needed!
        if ((titleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.titleLayout = new StaticLayout(title,
                    titlePaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        // Create new static layout only if needed!
        if ((subtitleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.subtitleLayout = new StaticLayout(subtitle,
                    subtitlePaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        textLayoutsConfigured = true;
    }
}
 
Example 8
Project: airgram   File: SecretPhotoViewer.java   Source Code and License 6 votes vote down vote up
private void updateSecretTimeText() {
    if (currentMessageObject == null) {
        return;
    }
    String str = currentMessageObject.getSecretTimeString();
    if (str == null) {
        return;
    }
    if (currentInfoString == null || !currentInfoString.equals(str)) {
        currentInfoString = str;
        infoWidth = (int)Math.ceil(infoPaint.measureText(currentInfoString));
        CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END);
        infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        invalidate();
    }
}
 
Example 9
Project: airgram   File: HintDialogCell.java   Source Code and License 6 votes vote down vote up
public void checkUnreadCounter(int mask) {
    if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
        return;
    }
    TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id);
    if (dialog != null && dialog.unread_count != 0) {
        if (lastUnreadCount != dialog.unread_count) {
            lastUnreadCount = dialog.unread_count;
            String countString = String.format("%d", dialog.unread_count);
            countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString)));
            countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
            if (mask != 0) {
                invalidate();
            }
        }
    } else if (countLayout != null) {
        if (mask != 0) {
            invalidate();
        }
        lastUnreadCount = 0;
        countLayout = null;
    }
}
 
Example 10
Project: airgram   File: LetterDrawable.java   Source Code and License 6 votes vote down vote up
public void setTitle(String title) {
    stringBuilder.setLength(0);
    if (title != null && title.length() > 0) {
        stringBuilder.append(title.substring(0, 1));
    }

    if (stringBuilder.length() > 0) {
        String text = stringBuilder.toString().toUpperCase();
        try {
            textLayout = new StaticLayout(text, namePaint, AndroidUtilities.dp(100), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            if (textLayout.getLineCount() > 0) {
                textLeft = textLayout.getLineLeft(0);
                textWidth = textLayout.getLineWidth(0);
                textHeight = textLayout.getLineBottom(0);
            }
        } catch (Exception e) {
            FileLog.e("tmessages", e);
        }
    } else {
        textLayout = null;
    }
}
 
Example 11
Project: Renrentou   File: CountDownView.java   Source Code and License 6 votes vote down vote up
private void init() {
    circlePaint = new Paint();
    circlePaint.setAntiAlias(true);
    circlePaint.setDither(true);
    circlePaint.setColor(backgroundColor);
    circlePaint.setStyle(Paint.Style.FILL);

    textPaint = new TextPaint();
    textPaint.setAntiAlias(true);
    textPaint.setDither(true);
    textPaint.setColor(textColor);
    textPaint.setTextSize(textSize);
    textPaint.setTextAlign(Paint.Align.CENTER);

    borderPaint = new Paint();
    borderPaint.setAntiAlias(true);
    borderPaint.setDither(true);
    borderPaint.setColor(borderColor);
    borderPaint.setStrokeWidth(borderWidth);
    borderPaint.setStyle(Paint.Style.STROKE);

    int textWidth = (int) textPaint.measureText(text.substring(0, (text.length() + 1) / 2));
    staticLayout = new StaticLayout(text, textPaint, textWidth, Layout.Alignment.ALIGN_NORMAL, 1F, 0, false);
}
 
Example 12
Project: XERUNG   File: MaterialMultiAutoCompleteTextView.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
      Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
      Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 13
Project: XERUNG   File: MaterialEditText.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
        Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
        Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 14
Project: XERUNG   File: MaterialAutoCompleteTextView.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
      Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
      Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 15
Project: XERUNG   File: MaterialMultiAutoCompleteTextView.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
      Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
      Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 16
Project: XERUNG   File: MaterialEditText.java   Source Code and License 6 votes vote down vote up
/**
 * @return True, if adjustments were made that require the view to be invalidated.
 */
private boolean adjustBottomLines() {
  // Bail out if we have a zero width; lines will be adjusted during next layout.
  if (getWidth() == 0) {
    return false;
  }
  int destBottomLines;
  textPaint.setTextSize(bottomTextSize);
  if (tempErrorText != null || helperText != null) {
    Layout.Alignment alignment = (getGravity() & Gravity.RIGHT) == Gravity.RIGHT || isRTL() ?
        Layout.Alignment.ALIGN_OPPOSITE : (getGravity() & Gravity.LEFT) == Gravity.LEFT ?
        Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_CENTER;
    textLayout = new StaticLayout(tempErrorText != null ? tempErrorText : helperText, textPaint, getWidth() - getBottomTextLeftOffset() - getBottomTextRightOffset() - getPaddingLeft() - getPaddingRight(), alignment, 1.0f, 0.0f, true);
    destBottomLines = Math.max(textLayout.getLineCount(), minBottomTextLines);
  } else {
    destBottomLines = minBottomLines;
  }
  if (bottomLines != destBottomLines) {
    getBottomLinesAnimator(destBottomLines).start();
  }
  bottomLines = destBottomLines;
  return true;
}
 
Example 17
Project: ChangeTabLayout   File: ChangeTextView.java   Source Code and License 6 votes vote down vote up
private void resetting(){
        float size;
        //字体随滑动变化
        if (level == 5000) {
            size = textSize * 1.1f;
        }else if(level == 10000 || level == 0){
            size = textSize * 1f;
        }else{
            float value = (level / 5000f) - 1f;
            size = textSize + textSize * (1 - Math.abs(value))* 0.1f;
        }

        mTextPaint.setTextSize(size);
        mTextPaint.setColor(defaultTabTextColor);
        int num = (getMeasuredWidth() - indicatorPadding) / (int) size; // 一行可以放下的字数,默认放置两行文字

//        mStaticLayout = new StaticLayout(text, mTextPaint, getMeasuredWidth() - indicatorPadding, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, false);
        mStaticLayout = new StaticLayout(text, 0, text.length() > num * 2 ?  num * 2 : text.length(), mTextPaint, getMeasuredWidth() - indicatorPadding,
                Layout.Alignment.ALIGN_NORMAL, 1.0F, 0.0F, false);

    }
 
Example 18
Project: CommentView   File: CanvasTextArea.java   Source Code and License 6 votes vote down vote up
private Layout makeSingleLayout(int i, BoringLayout.Metrics metrics, int i2, Alignment alignment, boolean z, TextUtils.TruncateAt truncateAt, boolean z2) {
    BoringLayout.Metrics isBoring;
    if (metrics == UNKNOWN_BORING) {
        isBoring = BoringLayout.isBoring(this.mText, this.mPaint, this.mBoring);
        if (isBoring != null) {
            this.mBoring = isBoring;
        }
    } else {
        isBoring = metrics;
    }
    if (isBoring != null) {
        if (isBoring.width <= i && (truncateAt == null || isBoring.width <= i2)) {
            return BoringLayout.make(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, isBoring, this.mIncludeFontPadding);
        } else if (z && isBoring.width <= i) {
            return BoringLayout.make(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, isBoring, this.mIncludeFontPadding, truncateAt, i2);
        } else if (z) {
            return StaticLayoutWithMaxLines.create(this.mText, 0, this.mText.length(), this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding, truncateAt, i2, this.mMaxLines);
        } else {
            return new StaticLayout(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding);
        }
    } else if (z) {
        return StaticLayoutWithMaxLines.create(this.mText, 0, this.mText.length(), this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding, truncateAt, i2, this.mMaxLines);
    } else {
        return new StaticLayout(this.mText, this.mPaint, i, alignment, this.mLineSpacingMult, this.mLineSpacingAdd, this.mIncludeFontPadding);
    }
}
 
Example 19
Project: Sega   File: AutoResizeTextView.java   Source Code and License 6 votes vote down vote up
/**
 * Sets the text size of a clone of the view's {@link TextPaint} object
 * and uses a {@link StaticLayout} instance to measure the height of the text.
 *
 * @param source
 * @param availableWidthPixels
 * @param textSizePixels
 * @return the height of the text when placed in a view
 * with the specified width
 * and when the text has the specified size.
 */
private int getTextHeightPixels(
        CharSequence source,
        int availableWidthPixels,
        float textSizePixels) {
    // Make a copy of the original TextPaint object
    // since the object gets modified while measuring
    // (see also the docs for TextView.getPaint()
    // which states to access it read-only)
    TextPaint textPaintCopy = new TextPaint(getPaint());
    textPaintCopy.setTextSize(textSizePixels);
    // Measure using a StaticLayout instance
    StaticLayout staticLayout = new StaticLayout(
            source,
            textPaintCopy,
            availableWidthPixels,
            Layout.Alignment.ALIGN_NORMAL,
            mLineSpacingMultiplier,
            mLineSpacingExtra,
            true);
    return staticLayout.getHeight();
}
 
Example 20
Project: Ec2m   File: FadeInText.java   Source Code and License 6 votes vote down vote up
/**
     * 绘制文字
     *
     * @param canvas 画布
     */
    private void drawText(Canvas canvas, String textString) {
        textRect.left = getPaddingLeft();
        textRect.top = getPaddingTop();
        textRect.right = getWidth() - getPaddingRight();
        textRect.bottom = getHeight() - getPaddingBottom();


        TextPaint textPaint = new TextPaint();
//        textPaint.setARGB(0xFF, 0xFF, 0, 0);
        textPaint.setTextSize(50.0F);
        textPaint.setAntiAlias(true);
/** * aboutTheGame :要 绘制 的 字符串 ,textPaint(TextPaint 类型)设置了字符串格式及属性 的画笔,getWidth()为设置 画多宽后 换行,后面的参数是对齐方式... */
        StaticLayout layout = new StaticLayout(textString,textPaint,getWidth(), Layout.Alignment.ALIGN_NORMAL,1.0F,0.0F,true);
        canvas.save();
        canvas.translate(10,10);
        layout.draw(canvas);
        canvas.restore();//别忘了restore

    }
 
Example 21
Project: PlusGram   File: CustomHintDialogCell.java   Source Code and License 6 votes vote down vote up
public void checkUnreadCounter(int mask) {
    if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
        return;
    }
    TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id);
    if (dialog != null && dialog.unread_count != 0) {
        if (lastUnreadCount != dialog.unread_count) {
            lastUnreadCount = dialog.unread_count;
            String countString = String.format("%d", dialog.unread_count);
            countWidth = Math.max(AndroidUtilities.dp(7), (int) Math.ceil(countPaint.measureText(countString)));
            countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
            if (mask != 0) {
                invalidate();
            }
        }
    } else if (countLayout != null) {
        if (mask != 0) {
            invalidate();
        }
        lastUnreadCount = 0;
        countLayout = null;
    }
}
 
Example 22
Project: PlusGram   File: SecretPhotoViewer.java   Source Code and License 6 votes vote down vote up
private void updateSecretTimeText() {
    if (currentMessageObject == null) {
        return;
    }
    String str = currentMessageObject.getSecretTimeString();
    if (str == null) {
        return;
    }
    if (currentInfoString == null || !currentInfoString.equals(str)) {
        currentInfoString = str;
        infoWidth = (int)Math.ceil(infoPaint.measureText(currentInfoString));
        CharSequence str2 = TextUtils.ellipsize(currentInfoString, infoPaint, infoWidth, TextUtils.TruncateAt.END);
        infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        invalidate();
    }
}
 
Example 23
Project: PlusGram   File: HintDialogCell.java   Source Code and License 6 votes vote down vote up
public void checkUnreadCounter(int mask) {
    if (mask != 0 && (mask & MessagesController.UPDATE_MASK_READ_DIALOG_MESSAGE) == 0 && (mask & MessagesController.UPDATE_MASK_NEW_MESSAGE) == 0) {
        return;
    }
    TLRPC.TL_dialog dialog = MessagesController.getInstance().dialogs_dict.get(dialog_id);
    if (dialog != null && dialog.unread_count != 0) {
        if (lastUnreadCount != dialog.unread_count) {
            lastUnreadCount = dialog.unread_count;
            String countString = String.format("%d", dialog.unread_count);
            countWidth = Math.max(AndroidUtilities.dp(12), (int) Math.ceil(countPaint.measureText(countString)));
            countLayout = new StaticLayout(countString, countPaint, countWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
            if (mask != 0) {
                invalidate();
            }
        }
    } else if (countLayout != null) {
        if (mask != 0) {
            invalidate();
        }
        lastUnreadCount = 0;
        countLayout = null;
    }
}
 
Example 24
Project: GitHub   File: Utils.java   Source Code and License 5 votes vote down vote up
public static void drawMultilineText(Canvas c, String text,
                                     float x, float y,
                                     TextPaint paint,
                                     FSize constrainedToSize,
                                     MPPointF anchor, float angleDegrees) {

    StaticLayout textLayout = new StaticLayout(
            text, 0, text.length(),
            paint,
            (int) Math.max(Math.ceil(constrainedToSize.width), 1.f),
            Layout.Alignment.ALIGN_NORMAL, 1.f, 0.f, false);


    drawMultilineText(c, textLayout, x, y, paint, anchor, angleDegrees);
}
 
Example 25
Project: android-slidr   File: Slidr.java   Source Code and License 5 votes vote down vote up
private void drawText(Canvas canvas, String text, float x, float y, TextPaint paint, Layout.Alignment aligment) {
    canvas.save();
    {
        canvas.translate(x, y);
        final StaticLayout staticLayout = new StaticLayout(text, paint, (int) paint.measureText(text), aligment, 1.0f, 0, false);
        staticLayout.draw(canvas);
    }
    canvas.restore();
}
 
Example 26
Project: empty-state-recyclerview   File: ImageTextStateDisplay.java   Source Code and License 5 votes vote down vote up
public ImageTextStateDisplay(Context c, @NonNull Bitmap bitmap, @NonNull String title, @Nullable String subtitle) {
    DisplayMetrics dm = c.getResources().getDisplayMetrics();
    this.sixteenDp = (int)(16f * dm.density);

    // Setup default sizes
    setPadding(sixteenDp, sixteenDp, sixteenDp, sixteenDp);
    this.titleSpacing = (int)(4f * dm.scaledDensity);
    this.textImageSpacing = sixteenDp;

    // Setup title defaults
    this.titlePaint.setTextAlign(Paint.Align.CENTER);
    this.titlePaint.setTextSize(18f * dm.scaledDensity);
    this.titlePaint.setColor(Color.BLACK);
    this.title = title;

    // Default to a single line of text
    this.titleLayout = new StaticLayout(title,
            titlePaint,
            (int)titlePaint.measureText(title),
            Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0, false);

    // Setup subtitle defaults
    this.subtitlePaint.setTextSize(14f * dm.scaledDensity);
    this.subtitlePaint.setTextAlign(Paint.Align.CENTER);
    this.subtitlePaint.setColor(Color.GRAY);
    this.subtitle = (subtitle == null ? "Dank yo hommie future is a rapper sdlkfjsldjfslkdjfsldjfasdjfasljdfasjdflasjdflsajd" : subtitle);

    // Default to a single line of text
    this.subtitleLayout = new StaticLayout(this.subtitle,
            subtitlePaint,
            (int)subtitlePaint.measureText(this.subtitle),
            Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0, false);

    this.image = bitmap;
}
 
Example 27
Project: empty-state-recyclerview   File: ImageTextStateDisplay.java   Source Code and License 5 votes vote down vote up
private void configure(final int availableWidth) {
    if (!configured) {
        final int totalNeededPadding = getPaddingLeft() + getPaddingRight();

        // Create new static layout only if needed!
        if ((titleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.titleLayout = new StaticLayout(title,
                    titlePaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        // Create new static layout only if needed!
        if ((subtitleLayout.getWidth() + totalNeededPadding) > availableWidth) {
            this.subtitleLayout = new StaticLayout(subtitle,
                    subtitlePaint,
                    availableWidth,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        final int newImageSize = ((availableWidth + getPaddingLeft() + getPaddingRight()) / 3);
        this.image = Bitmap.createScaledBitmap(image, newImageSize, newImageSize, false);

        configured = true;
    }
}
 
Example 28
Project: empty-state-recyclerview   File: TextStateDisplay.java   Source Code and License 5 votes vote down vote up
public TextStateDisplay(Context c, @NonNull String title, @Nullable String subtitle) {
    DisplayMetrics dm = c.getResources().getDisplayMetrics();

    // Setup default sizes
    final int large = (int)(16f * dm.density);
    setPadding(large, large, large, large);
    this.titleSpacing = (int)(4f * dm.scaledDensity);

    // Setup title defaults
    this.titlePaint.setTextAlign(Paint.Align.CENTER);
    this.titlePaint.setTextSize(18f * dm.scaledDensity);
    this.titlePaint.setColor(Color.BLACK);
    this.title = title;

    // Default to a single line of text
    this.titleLayout = new StaticLayout(title,
            titlePaint,
            (int)titlePaint.measureText(title),
            Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0, false);

    // Setup subtitle defaults
    this.subtitlePaint.setTextSize(14f * dm.scaledDensity);
    this.subtitlePaint.setTextAlign(Paint.Align.CENTER);
    this.subtitlePaint.setColor(Color.GRAY);
    this.subtitle = subtitle;

    // Default to a single line of text
    this.subtitleLayout = new StaticLayout(subtitle,
            subtitlePaint,
            (int)subtitlePaint.measureText(subtitle),
            Layout.Alignment.ALIGN_NORMAL,
            1.0f, 0, false);
}
 
Example 29
Project: stynico   File: AutofitHelper.java   Source Code and License 5 votes vote down vote up
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width,
								DisplayMetrics displayMetrics)
{
       paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size,
												displayMetrics));
       StaticLayout layout = new StaticLayout(text, paint, (int)width,
										   Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
       return layout.getLineCount();
   }
 
Example 30
Project: Rotatable-Scalable-Font   File: WidgetTextContent.java   Source Code and License 5 votes vote down vote up
private void addText() {

        mTextPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, getResources().getDisplayMetrics()));
        if (!"roboto.ttf".equals(mTypeface)) {
            mTextPaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), mTypeface));
            mTextStrokePaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), mTypeface));
        }
        mTextPaint.setFakeBoldText(true);
        mTextPaint.setAntiAlias(true);
        mTextPaint.setShadowLayer(mShadowRadius, mShadowDisX, mShadowDisY, mShadowColor);

        mTextStrokePaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mTextSize, getResources().getDisplayMetrics()));
        mTextStrokePaint.setStrokeWidth(mStrokeWidth);
        mTextStrokePaint.setStyle(Paint.Style.STROKE);
        mTextStrokePaint.setFakeBoldText(true);
        mTextStrokePaint.setAntiAlias(true);

        if (mTextGravity == WidgetTextBean.GRAVITY_CENTER || mTextGravity == WidgetTextBean.GRAVITY_HORIZONTAL_CENTER) {
            mAlignment = StaticLayout.Alignment.ALIGN_CENTER;
        } else {
            mAlignment = StaticLayout.Alignment.ALIGN_NORMAL;
        }


        mLayout = new StaticLayout(applyLetterSpacing(mText), mTextPaint, mTextRect.width(), mAlignment, 0.9f, mLineSpace, false);
        mStrokeLayout = new StaticLayout(applyLetterSpacing(mText), mTextStrokePaint, mTextRect.width(), mAlignment, 0.9f, mLineSpace, false);

//        mTextWidth = mTextPaint.measureText(mText);;
        mTextWidth = mLayout.getWidth();

        mTextHeight = mStrokeLayout.getHeight() >= mLayout.getHeight() ? mStrokeLayout.getHeight() : mLayout.getHeight();

        initColor();

    }
 
Example 31
Project: LuaViewPlayground   File: AutofitHelper.java   Source Code and License 5 votes vote down vote up
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width,
                                DisplayMetrics displayMetrics) {
    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size,
            displayMetrics));
    StaticLayout layout = new StaticLayout(text, paint, (int)width,
            Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
    return layout.getLineCount();
}
 
Example 32
Project: airgram   File: BotHelpCell.java   Source Code and License 5 votes vote down vote up
public void setText(String text) {
    if (text == null || text.length() == 0) {
        setVisibility(GONE);
        return;
    }
    if (text != null && oldText != null && text.equals(oldText)) {
        return;
    }
    oldText = text;
    setVisibility(VISIBLE);
    if (AndroidUtilities.isTablet()) {
        width = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
    } else {
        width = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
    }
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle);
    stringBuilder.append(help);
    stringBuilder.append("\n\n");
    stringBuilder.append(text);
    MessageObject.addLinks(stringBuilder);
    stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, help.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    Emoji.replaceEmoji(stringBuilder, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
    try {
        textLayout = new StaticLayout(stringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
        width = 0;
        height = textLayout.getHeight() + AndroidUtilities.dp(4 + 18);
        int count = textLayout.getLineCount();
        for (int a = 0; a < count; a++) {
            width = (int) Math.ceil(Math.max(width, textLayout.getLineWidth(a) + textLayout.getLineLeft(a)));
        }
    } catch (Exception e) {
        FileLog.e("tmessage", e);
    }
    width += AndroidUtilities.dp(4 + 18);
}
 
Example 33
Project: airgram   File: ChatMessageCell.java   Source Code and License 5 votes vote down vote up
private void updateSecretTimeText(MessageObject messageObject) {
    if (messageObject == null || messageObject.isOut()) {
        return;
    }
    String str = messageObject.getSecretTimeString();
    if (str == null) {
        return;
    }
    infoWidth = (int) Math.ceil(infoPaint.measureText(str));
    CharSequence str2 = TextUtils.ellipsize(str, infoPaint, infoWidth, TextUtils.TruncateAt.END);
    infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    invalidate();
}
 
Example 34
Project: android-autofittextview   File: AutofitHelper.java   Source Code and License 5 votes vote down vote up
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width,
        DisplayMetrics displayMetrics) {
    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size,
            displayMetrics));
    StaticLayout layout = new StaticLayout(text, paint, (int)width,
            Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
    return layout.getLineCount();
}
 
Example 35
Project: airgram   File: SimpleTextView.java   Source Code and License 5 votes vote down vote up
private void createLayout(int width) {
    if (text != null) {
        try {
            CharSequence string = TextUtils.ellipsize(text, textPaint, width, TextUtils.TruncateAt.END);
            layout = new StaticLayout(string, 0, string.length(), textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

            /*if (metrics == null) {
                metrics = BoringLayout.isBoring(text, textPaint);
            }
            if (layout == null) {
                layout = BoringLayout.make(text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, metrics, false, TextUtils.TruncateAt.END, width);
            } else {
                layout = ((BoringLayout) layout).replaceOrMake(text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, metrics, false, TextUtils.TruncateAt.END, width);
            }*/

            /*if (spannableStringBuilder == null) {
                spannableStringBuilder = new SpannableStringBuilder(text);
                layout = new DynamicLayout(text, text, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false, TextUtils.TruncateAt.END, width);
            } else {
                spannableStringBuilder.replace(0, text.length(), text);
            }*/

            if (layout.getLineCount() > 0) {
                if ((gravity & Gravity.HORIZONTAL_GRAVITY_MASK) == Gravity.LEFT) {
                    offsetX = -(int) layout.getLineLeft(0);
                } else if (layout.getLineLeft(0) == 0) {
                    offsetX = (int) (width - layout.getLineWidth(0));
                } else {
                    offsetX = 0;
                }
            }
        } catch (Exception e) {
            //ignore
        }
    }
}
 
Example 36
Project: RTLMaterialSpinner   File: RtlMaterialSpinner.java   Source Code and License 5 votes vote down vote up
private int prepareBottomPadding() {

        int targetNbLines = minNbErrorLines;
        if (error != null) {
            staticLayout = new StaticLayout(error, textPaint, getWidth() - getPaddingRight() - getPaddingLeft(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
            int nbErrorLines = staticLayout.getLineCount();
            targetNbLines = Math.max(minNbErrorLines, nbErrorLines);
        }
        return targetNbLines;
    }
 
Example 37
Project: quidditchtimekeeper   File: AutoResizeTextView.java   Source Code and License 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 38
Project: AdvancedTextView   File: SelectableTextView.java   Source Code and License 5 votes vote down vote up
/**
 * 重绘文字,两端对齐
 *
 * @param canvas
 */
private void drawTextWithJustify(Canvas canvas) {
    // 文字画笔
    TextPaint textPaint = getPaint();
    textPaint.setColor(getCurrentTextColor());
    textPaint.drawableState = getDrawableState();

    String text_str = getText().toString();
    // 当前所在行的Y向偏移
    int currentLineOffsetY = getPaddingTop();
    currentLineOffsetY += getTextSize();

    Layout layout = getLayout();

    //循环每一行,绘制文字
    for (int i = 0; i < layout.getLineCount(); i++) {
        int lineStart = layout.getLineStart(i);
        int lineEnd = layout.getLineEnd(i);
        //获取到TextView每行中的内容
        String line_str = text_str.substring(lineStart, lineEnd);
        // 获取每行字符串的宽度(不包括字符间距)
        float desiredWidth = StaticLayout.getDesiredWidth(text_str, lineStart, lineEnd, getPaint());

        if (isLineNeedJustify(line_str)) {
            //最后一行不需要重绘
            if (i == layout.getLineCount() - 1) {
                canvas.drawText(line_str, getPaddingLeft(), currentLineOffsetY, textPaint);
            } else {
                drawJustifyTextForLine(canvas, line_str, desiredWidth, currentLineOffsetY);
            }
        } else {
            canvas.drawText(line_str, getPaddingLeft(), currentLineOffsetY, textPaint);
        }
        //更新行Y向偏移
        currentLineOffsetY += getLineHeight();
    }
}
 
Example 39
Project: Quran   File: AyahNumberView.java   Source Code and License 5 votes vote down vote up
public void setAyahString(@NonNull String suraAyah) {
  if (!suraAyah.equals(this.suraAyah)) {
    this.suraAyah = suraAyah;
    this.textLayout = new StaticLayout(suraAyah, textPaint, boxWidth,
        Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);
    invalidate();
  }
}
 
Example 40
Project: XERUNG   File: MaterialSpinner.java   Source Code and License 5 votes vote down vote up
private int prepareBottomPadding() {

        int targetNbLines = minNbErrorLines;
        if (error != null) {
            staticLayout = new StaticLayout(error, textPaint, getWidth() - getPaddingRight() - getPaddingLeft(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
            int nbErrorLines = staticLayout.getLineCount();
            targetNbLines = Math.max(minNbErrorLines, nbErrorLines);
        }
        return targetNbLines;
    }
 
Example 41
Project: XERUNG   File: MaterialSpinner.java   Source Code and License 5 votes vote down vote up
private int prepareBottomPadding() {

        int targetNbLines = minNbErrorLines;
        if (error != null) {
            staticLayout = new StaticLayout(error, textPaint, getWidth() - getPaddingRight() - getPaddingLeft(), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
            int nbErrorLines = staticLayout.getLineCount();
            targetNbLines = Math.max(minNbErrorLines, nbErrorLines);
        }
        return targetNbLines;
    }
 
Example 42
Project: android-slidr   File: Sushi.java   Source Code and License 5 votes vote down vote up
private void drawText(Canvas canvas, String text, float x, float y, TextPaint paint, Layout.Alignment aligment) {
    canvas.save();
    {
        canvas.translate(x, y);
        final StaticLayout staticLayout = new StaticLayout(text, paint, (int) paint.measureText(text), aligment, 1.0f, 0, false);
        staticLayout.draw(canvas);
    }
    canvas.restore();
}
 
Example 43
Project: RecyclerWheelPicker   File: RecyclerWheelPicker.java   Source Code and License 5 votes vote down vote up
private void drawUnitText(Canvas c) {
    if (null != mUnitText && !TextUtils.isEmpty(mUnitText)) {
        mUnitTextPaint.setColor(mUnitColor);
        mUnitTextPaint.setTextSize(mUnitSize);
        float startX = getWidth() - getPaddingRight() - StaticLayout.getDesiredWidth(mUnitText, 0, mUnitText.length(), mUnitTextPaint);
        Paint.FontMetrics fontMetrics = mUnitTextPaint.getFontMetrics();
        float startY = getVerticalSpace() / 2 + mUnitSize / 2 - fontMetrics.descent / 2;
        c.drawText(mUnitText, startX, startY, mUnitTextPaint);
    }
}
 
Example 44
Project: RecyclerWheelPicker   File: RecyclerWheelPicker.java   Source Code and License 5 votes vote down vote up
@Override
    public boolean drawChild(Canvas canvas, View child, long drawingTime) {
        // rotateX
        int centerY = getVerticalSpace() / 2;
        int childCenterY = child.getTop() + child.getHeight() / 2;
        float factor = (centerY - childCenterY) * 1f / centerY;
        float alphaFactor = 1 - 0.7f * Math.abs(factor);
        child.setAlpha(alphaFactor * alphaFactor * alphaFactor);
        float scaleFactor = 1 - 0.3f * Math.abs(factor);
        child.setScaleX(scaleFactor);
        child.setScaleY(scaleFactor);

        float rotateRadius = 2.0f * centerY / (float) Math.PI;
        float rad = (centerY - childCenterY) * 1f / rotateRadius;
        float offsetZ = rotateRadius * (1 - (float) Math.cos(rad));
        float rotateDeg = rad * 180 / (float) Math.PI;
        ViewCompat.setZ(child, -offsetZ);
        child.setRotationX(rotateDeg);

        float offsetY = centerY - childCenterY - rotateRadius * (float) Math.sin(rad) * 1.3f;
        child.setTranslationY(offsetY);

        // resize the text size if text can not be shown completely
        if (child instanceof TextView) {
            String data = ((TextView) child).getText().toString();
            if (((TextView) child).getTextSize() == mTextSize) {
                float finalTextSize = mTextSize;
                float dataStringW = StaticLayout.getDesiredWidth(data, 0, data.length(), ((TextView) child).getPaint());
                if (getHorizontalSpace() > 0 && dataStringW * 1.1f > getHorizontalSpace()) {
                    finalTextSize = getHorizontalSpace() / dataStringW / 1.1f * mTextSize;
                }
                ((TextView) child).setTextSize(TypedValue.COMPLEX_UNIT_PX, finalTextSize);
            }
        }

        return super.drawChild(canvas, child, drawingTime);

//        // parent centerY ,item centerY
//        int centerY = (getHeight() - getPaddingTop() - getPaddingBottom()) / 2;
//        int childCenterY = child.getTop() + child.getHeight() / 2;
//        // alpha
//        float factor = (centerY - childCenterY) * 1f / centerY;
//        float currentFactor = 1 - 0.7f * Math.abs(factor);
//        child.setAlpha(currentFactor * currentFactor * currentFactor);
//
//        // rotate radius
//        float rotateRadius = 2.5f * centerY / (float) Math.PI;
//        // deg
//        float rad = (centerY - childCenterY) * 1f / rotateRadius;
//        float rotateDeg = rad * 180 / (float) Math.PI;
//        // for camera
//        float offsetZ = rotateRadius * (1 - (float) Math.cos(rad));
//        canvas.save();
//        // offset Y for item rotate
//        float offsetY = centerY - childCenterY - rotateRadius * (float) Math.sin(rad);
//        canvas.translate(0, offsetY);
//        mCamera.save();
//        mCamera.translate(0, 0, offsetZ);
//        mCamera.rotateX(rotateDeg);
//        mCamera.getMatrix(mMatrix);
//        mCamera.restore();
//        mMatrix.preTranslate(-child.getWidth() / 2, -childCenterY);
//        mMatrix.postTranslate(child.getWidth() / 2, childCenterY);
//        canvas.concat(mMatrix);
//        super.drawChild(canvas, child, drawingTime);
//        canvas.restore();
//        return true;
    }
 
Example 45
Project: CustomAndroidOneSheeld   File: AutoResizeTextView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onTestSize(int suggestedSize, RectF availableSPace) {
    mPaint.setTextSize(suggestedSize);
    String text = getText().toString();
    boolean singleline = getMaxLines() == 1;
    if (singleline) {
        mTextRect.bottom = mPaint.getFontSpacing();
        mTextRect.right = mPaint.measureText(text);
    } else {
        StaticLayout layout = new StaticLayout(text, mPaint,
                mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
                mSpacingAdd, true);
        // return early if we have more lines
        if (getMaxLines() != NO_LINE_LIMIT
                && layout.getLineCount() > getMaxLines()) {
            return 1;
        }
        mTextRect.bottom = layout.getHeight();
        int maxWidth = -1;
        for (int i = 0; i < layout.getLineCount(); i++) {
            if (maxWidth < layout.getLineWidth(i)) {
                maxWidth = (int) layout.getLineWidth(i);
            }
        }
        mTextRect.right = maxWidth;
    }

    mTextRect.offsetTo(0, 0);
    if (availableSPace.contains(mTextRect)) {
        // may be too small, don't worry we will find the best match
        return -1;
    } else {
        // too big
        return 1;
    }
}
 
Example 46
Project: HeaderDialog   File: ContentTextViewJustified.java   Source Code and License 5 votes vote down vote up
private void drawScaledText(final String line, final Canvas canvas, final float y, final float desiredLineWidth, final TextPaint paint) {
    String[] words = line.split(" ");

    float lineWidthWithoutSpaces = StaticLayout.getDesiredWidth(line.replace(" ", ""), getPaint());
    float spacing = (desiredLineWidth - lineWidthWithoutSpaces) / (words.length - 1);

    float x = 0;
    for (String word : words) {
        float cw = StaticLayout.getDesiredWidth(word, paint);
        canvas.drawText(word, x, y, paint);
        x += cw + spacing;
    }
}
 
Example 47
Project: Pocket-Plays-for-Twitch   File: FontFitTextView.java   Source Code and License 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, Layout.Alignment.ALIGN_NORMAL, mSpacingMult, mSpacingAdd, true);
	return layout.getHeight();
}
 
Example 48
Project: DarkCalculator   File: AutofitHelper.java   Source Code and License 5 votes vote down vote up
private static int getLineCount(CharSequence text, TextPaint paint, float size, float width,
                                DisplayMetrics displayMetrics) {
    paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, size,
            displayMetrics));
    StaticLayout layout = new StaticLayout(text, paint, (int) width,
            Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
    return layout.getLineCount();
}
 
Example 49
Project: eyeRS   File: AutoResizeTextView.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public int onTestSize(int suggestedSize, RectF availableSPace) {
    mPaint.setTextSize(suggestedSize);
    String text = getText().toString();
    boolean singleline = getMaxLines() == 1;
    if (singleline) {
        mTextRect.bottom = mPaint.getFontSpacing();
        mTextRect.right = mPaint.measureText(text);
    } else {
        StaticLayout layout = new StaticLayout(text, mPaint,
                mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
                mSpacingAdd, true);
        // return early if we have more lines
        if (getMaxLines() != NO_LINE_LIMIT
                && layout.getLineCount() > getMaxLines()) {
            return 1;
        }
        mTextRect.bottom = layout.getHeight();
        int maxWidth = -1;
        for (int i = 0; i < layout.getLineCount(); i++) {
            if (maxWidth < layout.getLineWidth(i)) {
                maxWidth = (int) layout.getLineWidth(i);
            }
        }
        mTextRect.right = maxWidth;
    }

    mTextRect.offsetTo(0, 0);
    if (availableSPace.contains(mTextRect)) {
        // may be too small, don't worry we will find the best match
        return -1;
    } else {
        // too big
        return 1;
    }
}
 
Example 50
Project: mvvm-template   File: TableHandler.java   Source Code and License 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 51
Project: SDHtmlTextView   File: TableHandler.java   Source Code and License 5 votes vote down vote up
@Override
public void draw(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 = 0;

	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, 1f, 0f, true);

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

	}
}
 
Example 52
Project: FastTextView   File: FastTextView.java   Source Code and License 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  long start = System.currentTimeMillis();
  int width = MeasureSpec.getSize(widthMeasureSpec);
  if (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY) {
    if (mAttrsHelper.mMaxWidth != Integer.MAX_VALUE && width > mAttrsHelper.mMaxWidth) {
      width = mAttrsHelper.mMaxWidth;
    }
  }
  if (!TextUtils.isEmpty(mText) && width > 0 &&
      (mLayout == null || width < mLayout.getWidth()
          || (width > mLayout.getWidth() && mLayout.getLineCount() > 1))) {
    if (mEnableLayoutCache) {
      mLayout = TextLayoutCache.STATIC_LAYOUT_CACHE.get(mText);
      if (mLayout == null) {
        mLayout = makeLayout(mText, width);
        TextLayoutCache.STATIC_LAYOUT_CACHE.put(mText, (StaticLayout) mLayout);
      }
    } else {
      mLayout = makeLayout(mText, width);
    }
  }
  if (Build.VERSION.SDK_INT <= 19 && mLayout != null) {
    // when <= api 19, maxLines can not be supported well.
    int height = mAttrsHelper.mMaxLines < mLayout.getLineCount() ? mLayout.getLineTop
        (mAttrsHelper.mMaxLines) : mLayout.getHeight();
    setMeasuredDimension(getMeasuredWidth(getPaddingLeft() + getPaddingRight() + mLayout
            .getWidth(), widthMeasureSpec),
        getMeasuredHeight(getPaddingTop() + getPaddingBottom() + height, heightMeasureSpec));
  } else {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }

  long end = System.currentTimeMillis();
  if (BuildConfig.DEBUG) {
    Log.d(TAG, "onMeasure cost:" + (end - start));
  }
}
 
Example 53
Project: PlusGram   File: EditTextCaption.java   Source Code and License 5 votes vote down vote up
@SuppressLint({"DrawAllocation"})
protected void onMeasure(int i, int i2) {
    try {
        super.onMeasure(i, i2);
    } catch (Throwable e) {
        FirebaseCrash.report(e);
        setMeasuredDimension(MeasureSpec.getSize(i), AndroidUtilities.dp(51.0f));
        FileLog.e("tmessages", e);
    }
    this.f399b = null;
    if (this.f398a != null && this.f398a.length() > 0) {
        CharSequence text = getText();
        if (text.length() > 1 && text.charAt(0) == '@') {
            int indexOf = TextUtils.indexOf(text, ' ');
            if (indexOf != -1) {
                TextPaint paint = getPaint();
                int ceil = (int) Math.ceil((double) paint.measureText(text, 0, indexOf + 1));
                int measuredWidth = (getMeasuredWidth() - getPaddingLeft()) - getPaddingRight();
                this.f400c = text.subSequence(0, indexOf + 1).length();
                CharSequence ellipsize = TextUtils.ellipsize(this.f398a, paint, (float) (measuredWidth - ceil), TruncateAt.END);
                this.f401d = ceil;
                try {
                    this.f399b = new StaticLayout(ellipsize, getPaint(), measuredWidth - ceil, Alignment.ALIGN_NORMAL, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT, 0.0f, false);
                    if (this.f399b.getLineCount() > 0) {
                        this.f401d = (int) (((float) this.f401d) + (-this.f399b.getLineLeft(0)));
                    }
                    this.f402e = ((getMeasuredHeight() - this.f399b.getLineBottom(0)) / 2) + AndroidUtilities.dp(0.5f);
                } catch (Throwable e2) {
                    FirebaseCrash.report(e2);
                    FileLog.e("tmessages", e2);
                }
            }
        }
    }
}
 
Example 54
Project: PlusGram   File: BotHelpCell.java   Source Code and License 5 votes vote down vote up
public void setText(String text) {
    if (text == null || text.length() == 0) {
        setVisibility(GONE);
        return;
    }
    if (text != null && oldText != null && text.equals(oldText)) {
        return;
    }
    oldText = text;
    setVisibility(VISIBLE);
    if (AndroidUtilities.isTablet()) {
        width = (int) (AndroidUtilities.getMinTabletSide() * 0.7f);
    } else {
        width = (int) (Math.min(AndroidUtilities.displaySize.x, AndroidUtilities.displaySize.y) * 0.7f);
    }
    SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
    String help = LocaleController.getString("BotInfoTitle", R.string.BotInfoTitle);
    stringBuilder.append(help);
    stringBuilder.append("\n\n");
    stringBuilder.append(text);
    MessageObject.addLinks(stringBuilder);
    stringBuilder.setSpan(new TypefaceSpan(AndroidUtilities.getTypeface("fonts/rmedium.ttf")), 0, help.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    Emoji.replaceEmoji(stringBuilder, textPaint.getFontMetricsInt(), AndroidUtilities.dp(20), false);
    try {
    textLayout = new StaticLayout(stringBuilder, textPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    width = 0;
    height = textLayout.getHeight() + AndroidUtilities.dp(4 + 18);
    int count = textLayout.getLineCount();
    for (int a = 0; a < count; a++) {
        width = (int) Math.ceil(Math.max(width, textLayout.getLineWidth(a) + textLayout.getLineLeft(a)));
    }
    } catch (Exception e) {
        FileLog.e("tmessage", e);
    }
    width += AndroidUtilities.dp(4 + 18);
}
 
Example 55
Project: Markwon   File: TableRowSpan.java   Source Code and License 5 votes vote down vote up
@Override
public int getSize(
        @NonNull Paint paint,
        CharSequence text,
        @IntRange(from = 0) int start,
        @IntRange(from = 0) int end,
        @Nullable Paint.FontMetricsInt fm) {

    // it's our absolute requirement to have width of the canvas here... because, well, it changes
    // the way we draw text. So, if we do not know the width of canvas we cannot correctly measure our text

    if (layouts.size() > 0) {

        if (fm != null) {

            int max = 0;
            for (StaticLayout layout : layouts) {
                final int height = layout.getHeight();
                if (height > max) {
                    max = height;
                }
            }

            // we store actual height
            height = max;

            // but apply height with padding
            final int padding = theme.tableCellPadding() * 2;

            fm.ascent = -(max + padding);
            fm.descent = 0;

            fm.top = fm.ascent;
            fm.bottom = 0;
        }
    }

    return width;
}
 
Example 56
Project: PlusGram   File: ChatMessageCell.java   Source Code and License 5 votes vote down vote up
private void updateSecretTimeText(MessageObject messageObject) {
    if (messageObject == null || messageObject.isOut()) {
        return;
    }
    String str = messageObject.getSecretTimeString();
    if (str == null) {
        return;
    }
    infoWidth = (int) Math.ceil(infoPaint.measureText(str));
    CharSequence str2 = TextUtils.ellipsize(str, infoPaint, infoWidth, TextUtils.TruncateAt.END);
    infoLayout = new StaticLayout(str2, infoPaint, infoWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    invalidate();
}
 
Example 57
Project: showroom-android   File: EllipsizingTextView.java   Source Code and License 4 votes vote down vote up
private Layout createWorkingLayout(CharSequence workingText) {
    return new StaticLayout(workingText, getPaint(),
            getWidth() - getPaddingLeft() - getPaddingRight(),
            Alignment.ALIGN_NORMAL, lineSpacingMultiplier,
            lineAdditionalVerticalPadding, false /* includepad */);
}
 
Example 58
Project: dhbw-timetable-android   File: WeekdayView.java   Source Code and License 4 votes vote down vote up
@Override
public void onDraw(Canvas canvas) {
    paint.reset();
    textPaint.reset();
    drawGrid(canvas);
    if (!fit) fitRectsToParent();
    for (BackportAppointment a : eventRectangles.keySet()) {
        RectF rect = eventRectangles.get(a);

        textPaint.setColor(getResources().getColor(R.color.colorPrimary));
        // Draw the appointment rectangle
        canvas.drawRoundRect(new RectF(rect), dp(7), dp(7), textPaint);

        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14, getResources().getDisplayMetrics()));

        // Draw the course time
        canvas.save();
        Typeface currentTypeFace1 = textPaint.getTypeface();
        textPaint.setTypeface(Typeface.create(currentTypeFace1, Typeface.NORMAL));

        canvas.drawText(a.getStartTime() + " - " + a.getEndTime(), rect.left + 16, rect.top + dp(16), textPaint);

        if (a.getTitle().equals("Klausur")) {
            Log.i("1337", "" + (rect.bottom - rect.top));
        }

        // Draw info
        if (rect.bottom - rect.top > 180) {
            canvas.drawText(TextUtils.ellipsize(a.getInfo(), textPaint,
                    dp((int) (X_OFFSET * 1.75) + X_WIDTH) - 32, TextUtils.TruncateAt.END).toString(),
                    rect.left + 16, rect.bottom - 16, textPaint);
        }

        // Draw course title
        if (rect.bottom - rect.top > 60) {
            StaticLayout courseTitleLayout = new StaticLayout(
                    TextUtils.ellipsize(a.getTitle().trim(), textPaint, dp((int) (X_OFFSET * 1.75) + X_WIDTH) - 32, TextUtils.TruncateAt.END),
                    textPaint,
                    dp((int) (X_OFFSET * 1.75) + X_WIDTH) - 32,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.0f,
                    0.0f,
                    false);
            Typeface currentTypeFace = textPaint.getTypeface();
            Typeface bold = Typeface.create(currentTypeFace, Typeface.BOLD);
            textPaint.setTypeface(bold);
            canvas.save();
            canvas.translate(rect.left + 16, rect.top + 16 + dp(16));
            courseTitleLayout.draw(canvas);
        }

        // Reset
        canvas.restore();
    }
}
 
Example 59
Project: GitHub   File: Utils.java   Source Code and License 4 votes vote down vote up
public static void drawMultilineText(Canvas c, StaticLayout textLayout,
                                     float x, float y,
                                     TextPaint paint,
                                     MPPointF anchor, float angleDegrees) {

    float drawOffsetX = 0.f;
    float drawOffsetY = 0.f;
    float drawWidth;
    float drawHeight;

    final float lineHeight = paint.getFontMetrics(mFontMetricsBuffer);

    drawWidth = textLayout.getWidth();
    drawHeight = textLayout.getLineCount() * lineHeight;

    // Android sometimes has pre-padding
    drawOffsetX -= mDrawTextRectBuffer.left;

    // Android does not snap the bounds to line boundaries,
    //  and draws from bottom to top.
    // And we want to normalize it.
    drawOffsetY += drawHeight;

    // To have a consistent point of reference, we always draw left-aligned
    Paint.Align originalTextAlign = paint.getTextAlign();
    paint.setTextAlign(Paint.Align.LEFT);

    if (angleDegrees != 0.f) {

        // Move the text drawing rect in a way that it always rotates around its center
        drawOffsetX -= drawWidth * 0.5f;
        drawOffsetY -= drawHeight * 0.5f;

        float translateX = x;
        float translateY = y;

        // Move the "outer" rect relative to the anchor, assuming its centered
        if (anchor.x != 0.5f || anchor.y != 0.5f) {
            final FSize rotatedSize = getSizeOfRotatedRectangleByDegrees(
                    drawWidth,
                    drawHeight,
                    angleDegrees);

            translateX -= rotatedSize.width * (anchor.x - 0.5f);
            translateY -= rotatedSize.height * (anchor.y - 0.5f);
            FSize.recycleInstance(rotatedSize);
        }

        c.save();
        c.translate(translateX, translateY);
        c.rotate(angleDegrees);

        c.translate(drawOffsetX, drawOffsetY);
        textLayout.draw(c);

        c.restore();
    } else {
        if (anchor.x != 0.f || anchor.y != 0.f) {

            drawOffsetX -= drawWidth * anchor.x;
            drawOffsetY -= drawHeight * anchor.y;
        }

        drawOffsetX += x;
        drawOffsetY += y;

        c.save();

        c.translate(drawOffsetX, drawOffsetY);
        textLayout.draw(c);

        c.restore();
    }

    paint.setTextAlign(originalTextAlign);
}
 
Example 60
Project: AndroRW   File: MyService.java   Source Code and License 4 votes vote down vote up
public Bitmap drawMultilineTextToBitmap(Bitmap bitmap, String gText) {
    int scale = 1;
    android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bitmap = bitmap.copy(bitmapConfig, true);

    Canvas canvas = new Canvas(bitmap);

    // new antialiased Paint
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    // text color - #3D3D3D
    paint.setColor(Color.rgb(61, 61, 61));
    // text size in pixels
    paint.setTextSize(14 * scale);
    // text shadow
    paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);

    // set text width to canvas width minus 16dp padding
    int textWidth = canvas.getWidth() - 16 * scale;

    // init StaticLayout for text
    StaticLayout textLayout = new StaticLayout(
            gText, paint, textWidth, Layout.Alignment.ALIGN_CENTER, 1.0f, 0.0f, false);

    // get height of multiline text
    int textHeight = textLayout.getHeight();

    // get position of text's top left corner
    float x = (bitmap.getWidth() - textWidth) / 2;
    float y = (bitmap.getHeight() - textHeight) / 2;

    // draw text to the Canvas center
    canvas.save();
    canvas.translate(x, y);
    textLayout.draw(canvas);
    canvas.restore();

    return bitmap;
}