Java Code Examples for android.text.Layout#getDesiredWidth()

The following examples show how to use android.text.Layout#getDesiredWidth() . 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: AsyncTextPathView.java    From TextPathView with MIT License 6 votes vote down vote up
@Override
protected void initPath() {
    mDst.reset();
    mFontPath.reset();

    if (!TextUtils.isEmpty(mText)) {
        //获取宽高
        mTextWidth = Layout.getDesiredWidth(mText, mTextPaint);
        Paint.FontMetrics metrics = mTextPaint.getFontMetrics();
        mTextHeight = metrics.bottom - metrics.top;

        mTextPaint.getTextPath(mText, 0, mText.length(), 0f, -metrics.ascent, mFontPath);
        mPathMeasure.setPath(mFontPath, false);
        mLength = mPathMeasure.getLength();
    }

}
 
Example 2
Source File: SyncTextPathView.java    From TextPathView with MIT License 6 votes vote down vote up
@Override
protected void initPath() {
    mDst.reset();
    mFontPath.reset();

    if (!TextUtils.isEmpty(mText)) {
        //获取宽高
        mTextWidth = Layout.getDesiredWidth(mText, mTextPaint);
        Paint.FontMetrics metrics = mTextPaint.getFontMetrics();
        mTextHeight = metrics.bottom - metrics.top;

        mTextPaint.getTextPath(mText, 0, mText.length(), 0, -metrics.ascent, mFontPath);
        mPathMeasure.setPath(mFontPath, false);
        mLengthSum = mPathMeasure.getLength();
        //获取所有路径的总长度
        while (mPathMeasure.nextContour()) {
            mLengthSum += mPathMeasure.getLength();
        }
    }

}
 
Example 3
Source File: TMReminderTagsView.java    From Virtualview-Android with MIT License 6 votes vote down vote up
public void setTags(String[] tags) {
    if (tags != null && this.tags != tags) {
        this.tags = tags;
        tagsWidth = 0;
        tagsHeight = (int) ((textFontMetrics.descent - textFontMetrics.ascent) + 0.5f);
        this.eachTagWidth = new int[tags.length];
        for (int i = 0; i < tags.length; i++) {
            int tagWdith = (int) (Layout.getDesiredWidth(tags[i] != null ? tags[i] : "", textPaint) + 0.5f) + 2 * hPadding;
            eachTagWidth[i] = tagWdith;
            tagsWidth += tagWdith;
            if (i < tags.length - 1) {
                tagsWidth += tagsGap;
            }
        }
        requestLayout();
        invalidate();
    }
}
 
Example 4
Source File: WebappUrlBar.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Show the end of the URL rather than the beginning.
 */
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
        int oldTop, int oldRight, int oldBottom) {
    Layout layout = mUrlBar.getLayout();
    if (layout == null) return;

    // Android doesn't account for the compound Drawable in its width calculations, leading to
    // improper scrolling and even Android improperly placing the horizontal fade in its
    // TextView calculation.  Get around it by calculating that width manually: crbug.com/303908
    int urlBarWidth = mUrlBar.getWidth();
    int iconWidth =
            mCurrentIconResource == 0 ? 0 : mIconResourceWidths.get(mCurrentIconResource);
    int availableTextWidth = urlBarWidth - iconWidth;
    int desiredWidth = (int) Layout.getDesiredWidth(layout.getText(), layout.getPaint());

    if (desiredWidth > availableTextWidth) {
        mUrlBar.scrollTo(desiredWidth - availableTextWidth, 0);
    } else {
        mUrlBar.scrollTo(0, 0);
    }
}
 
Example 5
Source File: WebappUrlBar.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Show the end of the URL rather than the beginning.
 */
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
        int oldTop, int oldRight, int oldBottom) {
    Layout layout = mUrlBar.getLayout();
    if (layout == null) return;

    // Android doesn't account for the compound Drawable in its width calculations, leading to
    // improper scrolling and even Android improperly placing the horizontal fade in its
    // TextView calculation.  Get around it by calculating that width manually: crbug.com/303908
    int urlBarWidth = mUrlBar.getWidth();
    int iconWidth =
            mCurrentIconResource == 0 ? 0 : mIconResourceWidths.get(mCurrentIconResource);
    int availableTextWidth = urlBarWidth - iconWidth;
    int desiredWidth = (int) Layout.getDesiredWidth(layout.getText(), layout.getPaint());

    if (desiredWidth > availableTextWidth) {
        mUrlBar.scrollTo(desiredWidth - availableTextWidth, 0);
    } else {
        mUrlBar.scrollTo(0, 0);
    }
}
 
Example 6
Source File: WebappUrlBar.java    From AndroidChromium with Apache License 2.0 6 votes vote down vote up
/**
 * Show the end of the URL rather than the beginning.
 */
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft,
        int oldTop, int oldRight, int oldBottom) {
    Layout layout = mUrlBar.getLayout();
    if (layout == null) return;

    // Android doesn't account for the compound Drawable in its width calculations, leading to
    // improper scrolling and even Android improperly placing the horizontal fade in its
    // TextView calculation.  Get around it by calculating that width manually: crbug.com/303908
    int urlBarWidth = mUrlBar.getWidth();
    int iconWidth =
            mCurrentIconResource == 0 ? 0 : mIconResourceWidths.get(mCurrentIconResource);
    int availableTextWidth = urlBarWidth - iconWidth;
    int desiredWidth = (int) Layout.getDesiredWidth(layout.getText(), layout.getPaint());

    if (desiredWidth > availableTextWidth) {
        mUrlBar.scrollTo(desiredWidth - availableTextWidth, 0);
    } else {
        mUrlBar.scrollTo(0, 0);
    }
}
 
Example 7
Source File: MeiTextPathView.java    From kAndroid with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化文字路径
 */
private void initTextPath() {
    mPathLength = 0;
    mFontPath.reset();
    mDstPath.reset();

    if (null == mText || mText.equals("")) {
        mText = "mei_s";
    }
    mTextWidth = Layout.getDesiredWidth(mText, mPaint);
    Paint.FontMetrics metrics = mPaint.getFontMetrics();
    mTextHeight = metrics.bottom - metrics.top;

    mPaint.getTextPath(mText, 0, mText.length(), 0, -metrics.ascent, mFontPath);
    mPathMeasure.setPath(mFontPath, false);

    mPathLength = mPathMeasure.getLength();
    while (mPathMeasure.nextContour()) {
        mPathLength += mPathMeasure.getLength();
    }

    if (mAutoStart) {
        post(new Runnable() {
            @Override
            public void run() {
                startAnimation();
            }
        });
    }
}
 
Example 8
Source File: ThermometerView.java    From ThermometerView with MIT License 5 votes vote down vote up
public void initConfig() {
    if (minThermometerRadius >= maxThermometerRadius) {
        throw new UnsupportedOperationException("温度计形状设置有误。");
    }
    if (minMercuryRadius >= maxMercuryRadius || minMercuryRadius >= minThermometerRadius) {
        throw new UnsupportedOperationException("水银形状设置有误。");
    }
    if (minScaleValue >= maxScaleValue) {
        throw new UnsupportedOperationException("刻度值设置不正确");
    }
    setResetCurValue(curScaleValue);

    sumScaleValue = (maxScaleValue - minScaleValue) * 10;

    mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);

    mLinePaint = new Paint();
    mLinePaint.setAntiAlias(true);
    mLinePaint.setStyle(Paint.Style.FILL);
    mLinePaint.setStrokeWidth(scaleLineWidth);

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setStyle(Paint.Style.FILL);

    String title = "℃";
    mTextPaint.setTextSize(unitTextSize);
    textWidth = Layout.getDesiredWidth(title, mTextPaint);
    Paint.FontMetricsInt fmi = mTextPaint.getFontMetricsInt();
    titleHeight = -(float) (fmi.bottom + fmi.top);

    this.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // 关闭硬件加速,否则阴影无效
}
 
Example 9
Source File: WXTextDomObject.java    From ucar-weex-core with Apache License 2.0 5 votes vote down vote up
/** package **/ float getTextWidth(TextPaint textPaint,float outerWidth, boolean forceToDesired) {
  float textWidth;
  if (forceToDesired) {
    textWidth = outerWidth;
  } else {
    float desiredWidth = Layout.getDesiredWidth(spanned, textPaint);
    if (CSSConstants.isUndefined(outerWidth) || desiredWidth < outerWidth) {
      textWidth = desiredWidth;
    } else {
      textWidth = outerWidth;
    }
  }
  return textWidth;
}
 
Example 10
Source File: SingleLineTextView.java    From FastTextView with Apache License 2.0 5 votes vote down vote up
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  if (mLayout == null && !TextUtils.isEmpty(mText)) {
    BoringLayout.Metrics fm = new BoringLayout.Metrics();
    fm.width = (int) Layout.getDesiredWidth(mText, mTextPaint);
    mLayout = BoringLayout.make(mText, mTextPaint, MeasureSpec.getSize(widthMeasureSpec),
        TextViewAttrsHelper.getLayoutAlignment(this, getGravity()), mAttrsHelper.mSpacingMultiplier, mAttrsHelper.mSpacingAdd, fm, true);
  }
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
 
Example 11
Source File: AlignToPointSpan.java    From revolution-irc with GNU General Public License v3.0 5 votes vote down vote up
public static CharSequence apply(TextView textView, CharSequence text) {
    if (text == null || !(text instanceof Spannable))
        return text;
    Spannable s = (Spannable) text;
    for (AlignToPointSpan span : s.getSpans(0, text.length(),
            AlignToPointSpan.class)) {
        span.mMargin = (int) Layout.getDesiredWidth(text, 0, s.getSpanStart(span.mAnchor),
                textView.getPaint());
    }
    return text;
}
 
Example 12
Source File: NumberProgressBar.java    From Android_Skin_2.0 with Apache License 2.0 5 votes vote down vote up
private RectF generateTextRectF() {
	FontMetrics fontMetrics = mTextPaint.getFontMetrics();
	final float height = fontMetrics.bottom - fontMetrics.top;

	String text = generateText();
	final float width = Layout.getDesiredWidth(text, mTextPaint) + 2 * mTextLRPad;

	return new RectF(0, 0, width, height);
}
 
Example 13
Source File: WXTextDomObject.java    From weex-uikit with MIT License 5 votes vote down vote up
/** package **/ float getTextWidth(TextPaint textPaint,float outerWidth, boolean forceToDesired) {
  float textWidth;
  if (forceToDesired) {
    textWidth = outerWidth;
  } else {
    float desiredWidth = Layout.getDesiredWidth(spanned, textPaint);
    if (CSSConstants.isUndefined(outerWidth) || desiredWidth < outerWidth) {
      textWidth = desiredWidth;
    } else {
      textWidth = outerWidth;
    }
  }
  return textWidth;
}
 
Example 14
Source File: ExpandTextView.java    From zone-sdk with MIT License 5 votes vote down vote up
/**
 * 得到最多行那个 最后一个字符的位置,与第一个位置 测出宽度 与 扩展字符 相加 如果大于行宽, 就把endPos--,知道小于。
 * 最后 截取字符  0-endPos 然后拼接  扩展字符 去显示即可!
 */
private void setExpand() {
    calExpand = true;
    Layout layout = getLayout();
    int endPos = layout.getLineEnd(maxLine - 1);
    int startPos = layout.getLineStart(maxLine - 1);
    TextPaint pt = getPaint();

    //如果宽度>测量宽度 就继续 --
    while (Layout.getDesiredWidth(getText(), startPos, endPos, pt) + Layout.getDesiredWidth(new SpannedString(EXPAND), pt) > layout.getWidth()
            && --endPos > startPos) {
    }
    SpannableStringBuilder nowSb = new SpannableStringBuilder(getText().subSequence(0, endPos)).append(EXPAND);
    setText(nowSb);
}
 
Example 15
Source File: CountSpan.java    From TokenAutoComplete with Apache License 2.0 4 votes vote down vote up
float getCountTextWidthForPaint(TextPaint paint) {
    return Layout.getDesiredWidth(countText, 0, countText.length(), paint);
}
 
Example 16
Source File: StringUtil.java    From Aria with Apache License 2.0 4 votes vote down vote up
/**
 * 获取字体长度
 */
public static int getTextLen(TextView textView) {
  TextPaint paint = textView.getPaint();
  return (int) Layout.getDesiredWidth(textView.getText().toString(), 0,
      textView.getText().length(), paint);
}
 
Example 17
Source File: WheelView.java    From xmpp with Apache License 2.0 4 votes vote down vote up
/**
 * Calculates control width and creates text layouts
 * 
 * @param widthSize
 *            the input layout width
 * @param mode
 *            the layout mode
 * @return the calculated control width
 */
private int calculateLayoutWidth(int widthSize, int mode) {
	initResourcesIfNecessary();

	int width = widthSize;

	int maxLength = getMaxTextLength();
	if (maxLength > 0) {
		float textWidth = Layout.getDesiredWidth("0",
				itemsPaint);
		itemsWidth = (int) (maxLength * textWidth);
	} else {
		itemsWidth = 0;
	}
	itemsWidth += ADDITIONAL_ITEMS_SPACE; // make it some more

	labelWidth = 0;
	if (label != null && label.length() > 0) {
		labelWidth = (int)Layout.getDesiredWidth(label,
				valuePaint);
	}

	boolean recalculate = false;
	if (mode == MeasureSpec.EXACTLY) {
		width = widthSize;
		recalculate = true;
	} else {
		width = itemsWidth + labelWidth + 2 * PADDING;
		if (labelWidth > 0) {
			width += LABEL_OFFSET;
		}

		// Check against our minimum width
		width = Math.max(width, getSuggestedMinimumWidth());

		if (mode == MeasureSpec.AT_MOST && widthSize < width) {
			width = widthSize;
			recalculate = true;
		}
	}

	if (recalculate) {
		// recalculate width
		int pureWidth = width - LABEL_OFFSET - 2 * PADDING;
		if (pureWidth <= 0) {
			itemsWidth = labelWidth = 0;
		}
		if (labelWidth > 0) {
			double newWidthItems = (double) itemsWidth * pureWidth
					/ (itemsWidth + labelWidth);
			itemsWidth = (int) newWidthItems;
			labelWidth = pureWidth - itemsWidth;
		} else {
			itemsWidth = pureWidth + LABEL_OFFSET; // no label
		}
	}

	if (itemsWidth > 0) {
		createLayouts(itemsWidth, labelWidth);
	}

	return width;
}
 
Example 18
Source File: ReflowTextAnimatorHelper.java    From reflow-animator with Apache License 2.0 4 votes vote down vote up
private static int getSectionWidth(@Nonnull Layout layout, int sectionStart, int sectionEnd) {
    CharSequence text = layout.getText();
    TextPaint paint = layout.getPaint();

    return (int) Layout.getDesiredWidth(text, sectionStart, sectionEnd, paint);
}
 
Example 19
Source File: TextUtil.java    From VideoOS-Android-SDK with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 改变外框大小,适应文字
 * 如果当前文字只有一行,则缩到外框适应文字大小
 * 如果文字有多行,则宽度不变,缩小高度到适应文字大小
 * 文字外框的位置不变
 *
 * @param view
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void adjustSize(TextView view) {
    if (view != null && view.getLayoutParams() != null) {
        /*
        //更好的实现方式,但是ios那边不支持这种方式
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        view.setLayoutParams(layoutParams);*/

        // 废弃的实现方式,使用WRAP_CONTENT最简单,且这种方式算出来的width有bug
        // @Deprecated
        /*int lineCount = Math.min(view.getLineCount(), getMaxLines(view));
        int width, height;
        if (lineCount > 1) {//多行,宽度不变,改变高度
            width = view.getWidth();
            height = view.getLineHeight() * lineCount + view.getPaddingTop() + view.getPaddingBottom();
        } else {//一行,改变宽度&高度
             Paint paint = view.getPaint();
            width = (int) paint.measureText(view.getText().toString()) + view.getPaddingLeft() + view.getPaddingRight();
            height = view.getLineHeight() + view.getPaddingTop() + view.getPaddingBottom();
        }*/

        int lineCount = Math.min(view.getLineCount(), getMaxLines(view));
        float width, height;
        if (lineCount > 1) {//多行,宽度不变,改变高度
            width = view.getWidth();
            height = view.getLineHeight() * lineCount + view.getPaddingTop() + view.getPaddingBottom();
        } else {//一行,改变宽度&高度
            width = view.getPaddingLeft() + Layout.getDesiredWidth(view.getText(), view.getPaint()) + view.getPaddingRight();
            height = view.getLineHeight() + view.getPaddingTop() + view.getPaddingBottom();
        }

        if (view.getLayoutParams() != null) {
            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
            layoutParams.width = (int) width;
            layoutParams.height = (int) height;
            view.setLayoutParams(layoutParams);
        }
    }
}