android.text.StaticLayout Java Examples

The following examples show how to use android.text.StaticLayout. 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: TextStateDisplay.java    From empty-state-recyclerview with MIT 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 - totalNeededPadding,
                    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 - totalNeededPadding,
                    Layout.Alignment.ALIGN_NORMAL,
                    1.15f, 0, false);
        }

        textLayoutsConfigured = true;
    }
}
 
Example #2
Source File: MaterialMultiAutoCompleteTextView.java    From XERUNG with Apache License 2.0 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 #3
Source File: MaterialMultiAutoCompleteTextView.java    From XERUNG with Apache License 2.0 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
Source File: LyricView.java    From RetroMusicPlayer with GNU General Public License v3.0 6 votes vote down vote up
public void setLyricFile(File file, String charsetName) {
    if (file != null && file.exists()) {
        try {
            setupLyricResource(new FileInputStream(file), charsetName);

            for (int i = 0; i < mLyricInfo.songLines.size(); i++) {

                StaticLayout staticLayout = new StaticLayout(mLyricInfo.songLines.get(i).content, mTextPaint,
                        (int) getRawSize(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_MAX_LENGTH),
                        Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);

                if (staticLayout.getLineCount() > 1) {
                    mEnableLineFeed = true;
                    mExtraHeight = mExtraHeight + (staticLayout.getLineCount() - 1) * mTextHeight;
                }

                mLineFeedRecord.add(i, mExtraHeight);

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    } else {
        invalidateView();
    }
}
 
Example #5
Source File: CollapsingTextHelper.java    From material-components-android with Apache License 2.0 6 votes vote down vote up
private StaticLayout createStaticLayout(int maxLines, float availableWidth, boolean isRtl) {
  StaticLayout textLayout = null;
  try {
    textLayout =
        StaticLayoutBuilderCompat.obtain(text, textPaint, (int) availableWidth)
            .setEllipsize(TruncateAt.END)
            .setIsRtl(isRtl)
            .setAlignment(ALIGN_NORMAL)
            .setIncludePad(false)
            .setMaxLines(maxLines)
            .build();
  } catch (StaticLayoutBuilderCompatException e) {
    Log.e(TAG, e.getCause().getMessage(), e);
  }

  return checkNotNull(textLayout);
}
 
Example #6
Source File: PopupAudioView.java    From Yahala-Messenger with MIT License 6 votes vote down vote up
public void updateProgress() {
    if (currentMessageObject == null) {
        return;
    }

    if (!seekBar.isDragging()) {
        seekBar.setProgress(currentMessageObject.audioProgress);
    }

    int duration = 0;
    if (!MediaController.getInstance().isPlayingAudio(currentMessageObject)) {
        duration = currentMessageObject.messageOwner.tl_message.media.audio.duration;
    } else {
        duration = currentMessageObject.audioProgressSec;
    }
    String timeString = String.format("%02d:%02d", duration / 60, duration % 60);
    if (lastTimeString == null || lastTimeString != null && !lastTimeString.equals(timeString)) {
        timeWidth = (int) Math.ceil(timePaint.measureText(timeString));
        timeLayout = new StaticLayout(timeString, timePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
    }
    invalidate();
}
 
Example #7
Source File: ChangeTextView.java    From ChangeTabLayout with Apache License 2.0 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 #8
Source File: HtmlTextView.java    From MousePaint with MIT License 6 votes vote down vote up
public void resizeText(int paramInt1, int paramInt2) {
    CharSequence localCharSequence = getText();
    if ((localCharSequence == null) || (localCharSequence.length() == 0) || (paramInt2 <= 0) || (paramInt1 <= 0))
        return;
    TextPaint localTextPaint = getPaint();
    StaticLayout localStaticLayout = new StaticLayout(localCharSequence, localTextPaint, paramInt1, Layout.Alignment.ALIGN_NORMAL, 1.25F, 0.0F, true);
    int i = localStaticLayout.getLineCount();
    int j = paramInt2 / (localStaticLayout.getHeight() / i);
    if (i > j) {
        int k = localStaticLayout.getLineStart(j - 1);
        int m = localStaticLayout.getLineEnd(j - 1);
        float f1 = localStaticLayout.getLineWidth(j - 1);
        float f2 = localTextPaint.measureText(this.mEllipsis);
        while (paramInt1 < f1 + f2) {
            m--;
            f1 = localTextPaint.measureText(localCharSequence.subSequence(k, m + 1).toString());
        }
        setText(localCharSequence.subSequence(0, m) + this.mEllipsis);
    }
    setMaxLines(j);
    this.mNeedsResize = false;
}
 
Example #9
Source File: DimensionsLabel.java    From Rhythm with Apache License 2.0 6 votes vote down vote up
@Override
public void draw(Canvas canvas, Rect drawableBounds) {
    final int intWidth = drawableBounds.width();
    // Make the label text based on width, height, and scale factor
    String text = prettyPrintDips(intWidth, mScaleFactor) + ' ' + MULTIPLY + ' '
            + prettyPrintDips(drawableBounds.height(), mScaleFactor);

    // Use StaticLayout, which will calculate text dimensions nicely, then position the box using Gravity.apply()
    // (although that's one instantiation per draw call...)
    // This is what happens if you're obsessed with perfection like me
    StaticLayout layout = new StaticLayout(text, mTextPaint, intWidth, Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false);
    Gravity.apply(mGravity, (int) (layout.getLineMax(0) + 0.5), layout.getHeight(), drawableBounds, mTemp);

    // Draw background
    canvas.drawRect(mTemp, mBackgroundPaint);

    // We have to translate the canvas ourselves, since layout can only draw itself at (0, 0)
    canvas.save();
    canvas.translate(mTemp.left, mTemp.top);
    layout.draw(canvas);
    canvas.restore();
}
 
Example #10
Source File: StepView.java    From StepView with Apache License 2.0 6 votes vote down vote up
private int measureStepsHeight() {
    textLayouts = new StaticLayout[steps.size()];
    textPaint.setTextSize(textSize);
    int max = 0;
    for (int i = 0; i < steps.size(); i++) {
        String text = steps.get(i);
        Layout.Alignment alignment =
                isRtl() ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL;
        textLayouts[i] = new StaticLayout(
                text,
                textPaint,
                getMeasuredWidth() / steps.size(),
                alignment,
                1,
                0,
                true
        );
        int height = textLayouts[i].getHeight();
        max = Math.max(height, max);
    }
    return max;
}
 
Example #11
Source File: TextSelectionHelper.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected int getLineHeight() {
    if (selectedView != null && selectedView.getMessageObject() != null) {
        MessageObject object = selectedView.getMessageObject();
        StaticLayout layout = null;
        if (isDescription) {
            layout = selectedView.getDescriptionlayout();
        } else if (selectedView.hasCaptionLayout()) {
            layout = selectedView.getCaptionLayout();
        } else if (object.textLayoutBlocks != null) {
            layout = object.textLayoutBlocks.get(0).textLayout;
        }
        if (layout == null) {
            return 0;
        }
        int lineHeight = layout.getLineBottom(0) - layout.getLineTop(0);
        return lineHeight;
    }
    return 0;
}
 
Example #12
Source File: DocumentPrintUtils.java    From secure-quick-reliable-login with MIT License 6 votes vote down vote up
public static int drawTextBlock(Canvas canvas, String text, Layout.Alignment alignment, TextPaint textPaint, int y, int margin) {
    int width = canvas.getWidth() - (margin * 2);

    StaticLayout staticLayout = new StaticLayout(
            text,
            textPaint,
            width,
            alignment,
            1,
            0,
            false);

    canvas.save();
    canvas.translate(margin, y);
    staticLayout.draw(canvas);
    canvas.restore();

    return staticLayout.getHeight();
}
 
Example #13
Source File: HintDialogCell.java    From TelePlus-Android with GNU General Public License v2.0 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(currentAccount).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(Theme.dialogs_countTextPaint.measureText(countString)));
            countLayout = new StaticLayout(countString, Theme.dialogs_countTextPaint, 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 #14
Source File: FlowTextHelperImpl.java    From Overchan-Android with GNU General Public License v3.0 6 votes vote down vote up
public static boolean flowText(SpannableStringBuilder ss, int width, int height, int textFullWidth, TextPaint textPaint) {
    StaticLayout l = new StaticLayout(ss, 0, ss.length(), textPaint, textFullWidth - width, Layout.Alignment.ALIGN_NORMAL, 1.0F, 0, false);
    int lines = 0;
    while (lines < l.getLineCount() && l.getLineBottom(lines) < height) ++lines;
    ++lines;
    
    int endPos;
    if (lines < l.getLineCount()) {
        endPos = l.getLineStart(lines);
    } else {
        return false;
    }
    if (ss.charAt(endPos-1) != '\n' && ss.charAt(endPos-1) != '\r') {
        if (ss.charAt(endPos-1) == ' ') {
            ss.replace(endPos-1, endPos, "\n");
        } else {
            ss.insert(endPos, "\n");
        }
    }
    
    ss.setSpan(new FloatingMarginSpan(lines, width), 0, endPos, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    return true;
}
 
Example #15
Source File: AutofitHelper.java    From kAndroid with Apache License 2.0 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 #16
Source File: ReflowText.java    From android-proguards with Apache License 2.0 5 votes vote down vote up
private Layout createLayout(ReflowData data, Context context, boolean enforceMaxLines) {
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    paint.setTextSize(data.textSize);
    paint.setColor(data.textColor);
    paint.setLetterSpacing(data.letterSpacing);
    if (data.fontName != null) {
        paint.setTypeface(FontUtil.get(context, data.fontName));
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        StaticLayout.Builder builder =  StaticLayout.Builder.obtain(
                data.text, 0, data.text.length(), paint, data.textWidth)
                .setLineSpacing(data.lineSpacingAdd, data.lineSpacingMult)
                .setBreakStrategy(data.breakStrategy);
        if (enforceMaxLines && data.maxLines != -1) {
            builder.setMaxLines(data.maxLines);
            builder.setEllipsize(TextUtils.TruncateAt.END);
        }
        return builder.build();
    } else {
        return new StaticLayout(
                data.text,
                paint,
                data.textWidth,
                Layout.Alignment.ALIGN_NORMAL,
                data.lineSpacingMult,
                data.lineSpacingAdd,
                true);
    }
}
 
Example #17
Source File: AutofitTextView.java    From UltimateAndroid with Apache License 2.0 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 #18
Source File: Utils.java    From StockChart-MPAndroidChart with MIT 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 #19
Source File: ChatBaseCell.java    From Yahala-Messenger with MIT License 5 votes vote down vote up
@SuppressLint("DrawAllocation")
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    try {
        if (currentMessageObject == null) {
            super.onLayout(changed, left, top, right, bottom);
            return;
        }

        if (changed || !wasLayout) {
            layoutWidth = getMeasuredWidth();
            layoutHeight = getMeasuredHeight();

            timeLayout = new StaticLayout(currentTimeString, currentTimePaint, timeWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            if (!media) {
                if (currentMessageObject.messageOwner.getOut() != 1) {
                    timeX = backgroundWidth - OSUtilities.dp(9) - timeWidth + (isChat ? OSUtilities.dp(52) : 0);
                } else {
                    timeX = layoutWidth - timeWidth - OSUtilities.dpf(38.5f);
                }
            } else {
                if (currentMessageObject.messageOwner.getOut() != 1) {
                    timeX = backgroundWidth - OSUtilities.dp(4) - timeWidth + (isChat ? OSUtilities.dp(52) : 0);
                } else {
                    timeX = layoutWidth - timeWidth - OSUtilities.dpf(42.0f);
                }
            }

            if (isAvatarVisible) {
                avatarImage.imageX = OSUtilities.dp(6);
                avatarImage.imageY = layoutHeight - OSUtilities.dp(45);
                avatarImage.imageW = OSUtilities.dp(42);
                avatarImage.imageH = OSUtilities.dp(42);
            }

            wasLayout = true;
        }
    } catch (Exception e) {
    }
}
 
Example #20
Source File: PageLoader.java    From MyBookshelf with GNU General Public License v3.0 5 votes vote down vote up
private void drawScaledText(Canvas canvas, String line, float lineWidth, TextPaint paint, float top, int y, List<TxtLine> txtLists) {
    float x = mMarginLeft;

    if (isFirstLineOfParagraph(line)) {
        canvas.drawText(indent, x, top, paint);
        float bw = StaticLayout.getDesiredWidth(indent, paint);
        x += bw;
        line = line.substring(readBookControl.getIndent());
    }
    int gapCount = line.length() - 1;
    int i = 0;

    TxtLine txtList = new TxtLine();//每一行pzl
    txtList.setCharsData(new ArrayList<>());//pzl

    float d = ((mDisplayWidth - (mMarginLeft + mMarginRight)) - lineWidth) / gapCount;
    for (; i < line.length(); i++) {
        String c = String.valueOf(line.charAt(i));
        float cw = StaticLayout.getDesiredWidth(c, paint);
        canvas.drawText(c, x, top, paint);
        //pzl
        TxtChar txtChar = new TxtChar();
        txtChar.setChardata(line.charAt(i));
        if (i == 0) txtChar.setCharWidth(cw + d / 2);
        if (i == gapCount) txtChar.setCharWidth(cw + d / 2);
        txtChar.setCharWidth(cw + d);
        ;//字宽
        //txtChar.Index = y;//每页每个字的位置
        txtList.getCharsData().add(txtChar);
        //pzl
        x += cw + d;
    }
    if (txtLists != null) {
        txtLists.set(y, txtList);//pzl
    }
}
 
Example #21
Source File: LrcView.java    From APlayer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获得单句歌词的高度,可能有多行
 */
private int getSingleLineHeight(String text) {
  StaticLayout staticLayout = new StaticLayout(text, mPaintForOtherLrc,
      getWidth() - getPaddingLeft() - getPaddingRight(), Layout.Alignment.ALIGN_CENTER,
      DEFAULT_SPACING_MULTI, DEFAULT_SPACING_PADDING, true);
  return staticLayout.getHeight();
}
 
Example #22
Source File: CollapsingTitleLayout.java    From android-proguards with Apache License 2.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private void createLayoutM(int width, float lineSpacingAdd) {
    layout = StaticLayout.Builder.obtain(displayText, 0, displayText.length(), paint,
            width - titleInsetStart - titleInsetEnd)
            .setLineSpacing(lineSpacingAdd, 1f)
            .setMaxLines(maxLines)
            .setEllipsize(TextUtils.TruncateAt.END)
            .setBreakStrategy(BREAK_STRATEGY)
            .build();
    lineCount = layout.getLineCount();
}
 
Example #23
Source File: SimpleTextView.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
private boolean createLayout(int width) {
    if (text != null) {
        try {
            if (leftDrawable != null) {
                width -= leftDrawable.getIntrinsicWidth();
                width -= drawablePadding;
            }
            if (rightDrawable != null) {
                width -= rightDrawable.getIntrinsicWidth();
                width -= drawablePadding;
            }
            CharSequence string = TextUtils.ellipsize(text, textPaint, width, TextUtils.TruncateAt.END);
            /*if (layout != null && TextUtils.equals(layout.getText(), string)) {
                calcOffset(width);
                return false;
            }*/
            layout = new StaticLayout(string, 0, string.length(), textPaint, width + AndroidUtilities.dp(8), Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
            calcOffset(width);
        } catch (Exception ignore) {

        }
    } else {
        layout = null;
        textWidth = 0;
        textHeight = 0;
    }
    invalidate();
    return true;
}
 
Example #24
Source File: Utils.java    From Ticket-Analysis with MIT 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
Source File: PigstyMode.java    From CatchPiggy with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 画文字提示
 */
private void drawText(Canvas canvas) {
    String text = null;
    if (!isCarDispatched) {
        if (isGameOver) {
            text = isWon ? mCarIsComingText : mPiggiesHasRunText;
        } else if (!isPiggyByCar) {
            text = mStartCatchText;
        } else {
            if (mCurrentLevel > 0) {
                text = String.format(mLevelStringFormat, mCurrentLevel);
            }
        }
        if (text != null) {
            StaticLayout staticLayout = new StaticLayout(text, mPaint, getWidth(), Layout.Alignment.ALIGN_NORMAL, 1, 0, true);
            canvas.save();
            canvas.translate(mWidth / 2, 0);
            staticLayout.draw(canvas);
            canvas.restore();
        }
    } else {
        if (isWon && !isAllPiggiesAreReady) {
            float y = (mHeight - mPaint.getFontMetricsInt().bottom - mPaint.getFontMetricsInt().top) / 2;
            canvas.drawText(mDragPigText, mWidth / 2, y, mPaint);
        }
    }
}
 
Example #26
Source File: PageLoader.java    From a with GNU General Public License v3.0 5 votes vote down vote up
private void drawScaledText(Canvas canvas, String line, float lineWidth, TextPaint paint, float top,int y,List<TxtLine> txtLists) {
    float x = mMarginLeft;

    if (isFirstLineOfParagraph(line)) {
        canvas.drawText(indent, x, top, paint);
        float bw = StaticLayout.getDesiredWidth(indent, paint);
        x += bw;
        line = line.substring(readBookControl.getIndent());
    }
    int gapCount = line.length() - 1;
    int i = 0;

    TxtLine txtList = new TxtLine();//每一行pzl
    txtList.CharsData = new ArrayList<TxtChar>();//pzl

    float d = ((mDisplayWidth - (mMarginLeft + mMarginRight)) - lineWidth) / gapCount;
    for (; i < line.length(); i++) {
        String c = String.valueOf(line.charAt(i));
        float cw = StaticLayout.getDesiredWidth(c, paint);
        canvas.drawText(c, x, top, paint);
        //pzl
        TxtChar txtChar = new TxtChar();
        txtChar.chardata = line.charAt(i);
        if(i==0) txtChar.charWidth = cw + d/2;
        if(i==gapCount) txtChar.charWidth = cw + d/2;
        txtChar.charWidth = cw + d;
        ;//字宽
        //txtChar.Index = y;//每页每个字的位置
        txtList.CharsData.add(txtChar);
        //pzl
        x += cw + d;
    }
    txtLists.set(y, txtList);//pzl

}
 
Example #27
Source File: FastTextView.java    From FastTextView with Apache License 2.0 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  long start = System.currentTimeMillis();
  int width = MeasureSpec.getSize(widthMeasureSpec);
  boolean exactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY;
  if (!exactly) {
    if (mAttrsHelper.mMaxWidth != Integer.MAX_VALUE && width > mAttrsHelper.mMaxWidth) {
      width = mAttrsHelper.mMaxWidth;
    }
  }
  if (width > 0) {
    width = width - getPaddingLeft() - getPaddingRight();
  }
  if (shouldResetStaticLayout(width, mText, mLayout)) {
    if (mEnableLayoutCache) {
      mLayout = TextLayoutCache.STATIC_LAYOUT_CACHE.get(mText);
      if (mLayout == null) {
        mLayout = makeLayout(mText, width, exactly);
        TextLayoutCache.STATIC_LAYOUT_CACHE.put(mText, (StaticLayout) mLayout);
      }
    } else {
      mLayout = makeLayout(mText, width, exactly);
    }
  }
  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 #28
Source File: EditTextOutline.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
protected void onDraw(Canvas canvas) {
    if (mCache != null && mStrokeColor != Color.TRANSPARENT) {
        if (mUpdateCachedBitmap) {
            final int w = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
            final int h = getMeasuredHeight();
            final String text = getText().toString();

            mCanvas.setBitmap(mCache);
            mCanvas.drawColor(0, PorterDuff.Mode.CLEAR);

            float strokeWidth = mStrokeWidth > 0 ? mStrokeWidth : (float)Math.ceil(getTextSize() / 11.5f);
            mPaint.setStrokeWidth(strokeWidth);
            mPaint.setColor(mStrokeColor);
            mPaint.setTextSize(getTextSize());
            mPaint.setTypeface(getTypeface());
            mPaint.setStyle(Paint.Style.FILL_AND_STROKE);

            StaticLayout sl = new StaticLayout(text, mPaint, w, Layout.Alignment.ALIGN_CENTER, 1, 0, true);

            mCanvas.save();
            float a = (h - getPaddingTop() - getPaddingBottom() - sl.getHeight()) / 2.0f;
            mCanvas.translate(getPaddingLeft(), a + getPaddingTop());
            sl.draw(mCanvas);
            mCanvas.restore();

            mUpdateCachedBitmap = false;
        }
        canvas.drawBitmap(mCache, 0, 0, mPaint);
    }
    super.onDraw(canvas);
}
 
Example #29
Source File: TextSelectionHelper.java    From Telegram with GNU General Public License v2.0 5 votes vote down vote up
public void drawCaption(boolean isOut, StaticLayout captionLayout, Canvas canvas) {
    if (isDescription) {
        return;
    }
    if (isOut) {
        selectionPaint.setColor(Theme.getColor(Theme.key_chat_outTextSelectionHighlight));
    } else {
        selectionPaint.setColor(Theme.getColor(key_chat_inTextSelectionHighlight));
    }
    drawSelection(canvas, captionLayout, selectionStart, selectionEnd);
}
 
Example #30
Source File: AutofitTextView.java    From UltimateAndroid with Apache License 2.0 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();
}