private static int getTextWidth(@Nullable final CharSequence text, final TextPaint paint) { if (TextUtils.isEmpty(text)) { return 0; } final int length = text.length(); final float[] widths = new float[length]; final int count; final Typeface savedTypeface = paint.getTypeface(); try { paint.setTypeface(getTextTypeface(text)); count = paint.getTextWidths(text, 0, length, widths); } finally { paint.setTypeface(savedTypeface); } int width = 0; for (int i = 0; i < count; i++) { width += Math.round(widths[i] + 0.5f); } return width; }
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()); } }
@Override public void createContent(InfoBarLayout layout) { super.createContent(layout); SpannableString message = new SpannableString(mMessageText); message.setSpan( new ClickableSpan() { @Override public void onClick(View view) { onLinkClicked(); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setUnderlineText(false); } }, mInlineLinkRangeStart, mInlineLinkRangeEnd, Spanned.SPAN_INCLUSIVE_INCLUSIVE); layout.setMessage(message); }
@Override protected void onDraw(Canvas canvas) { TextPaint textPaint = getPaint(); textPaint.setColor(getCurrentTextColor()); textPaint.drawableState = getDrawableState(); canvas.save(); if (topDown) { canvas.translate(getWidth(), 0); canvas.rotate(90); } else { canvas.translate(0, getHeight()); canvas.rotate(-90); } canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop()); getLayout().draw(canvas); canvas.restore(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public PendingAppWidgetHostView(Context context, LauncherAppWidgetInfo info, boolean disabledForSafeMode) { super(new ContextThemeWrapper(context, R.style.WidgetContainerTheme)); mLauncher = Launcher.getLauncher(context); mInfo = info; mStartState = info.restoreStatus; mIconLookupIntent = new Intent().setComponent(info.providerName); mDisabledForSafeMode = disabledForSafeMode; mPaint = new TextPaint(); mPaint.setColor(0xFFFFFFFF); mPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mLauncher.getDeviceProfile().iconTextSizePx, getResources().getDisplayMetrics())); setBackgroundResource(R.drawable.quantum_panel_dark); setWillNotDraw(false); if (Utilities.ATLEAST_LOLLIPOP) { setElevation(getResources().getDimension(R.dimen.pending_widget_elevation)); } }
private void initPaintObjects() { int labelTextSize = getResources().getDimensionPixelSize(R.dimen.label_text_size); paint = new Paint(Paint.ANTI_ALIAS_FLAG); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(labelTextSize); if (typeface != null) { textPaint.setTypeface(typeface); } textPaint.setColor(baseColor); baseAlpha = textPaint.getAlpha(); selectorPath = new Path(); selectorPath.setFillType(Path.FillType.EVEN_ODD); selectorPoints = new Point[3]; for (int i = 0; i < 3; i++) { selectorPoints[i] = new Point(); } }
public static StaticLayout generateStaticLayout(CharSequence text, TextPaint paint, int maxWidth, int smallWidth, int linesCount, int maxLines) { SpannableStringBuilder stringBuilder = new SpannableStringBuilder(text); int addedChars = 0; StaticLayout layout = new StaticLayout(text, paint, smallWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false); for (int a = 0; a < linesCount; a++) { Layout.Directions directions = layout.getLineDirections(a); if (layout.getLineLeft(a) != 0 || layout.isRtlCharAt(layout.getLineStart(a)) || layout.isRtlCharAt(layout.getLineEnd(a))) { maxWidth = smallWidth; } int pos = layout.getLineEnd(a); if (pos == text.length()) { break; } pos--; if (stringBuilder.charAt(pos + addedChars) == ' ') { stringBuilder.replace(pos + addedChars, pos + addedChars + 1, "\n"); } else if (stringBuilder.charAt(pos + addedChars) != '\n') { stringBuilder.insert(pos + addedChars, "\n"); addedChars++; } if (a == layout.getLineCount() - 1 || a == maxLines - 1) { break; } } return StaticLayoutEx.createStaticLayout(stringBuilder, paint, maxWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, dp(1), false, TextUtils.TruncateAt.END, maxWidth, maxLines); }
private void init() { mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); mTextPaint.setColor(mTextColor); if (mTextSizePx <= 0) { mTextSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_FONT_SIZE_SP, getResources().getDisplayMetrics()); } mTextPaint.setTextSize(mTextSizePx); mTypeface = MongolFont.get(MongolFont.QAGAN, mContext); mTextPaint.setTypeface(mTypeface); mTextPaint.linkColor = Color.BLUE; // initialize the layout, but the height still needs to be set final CharSequence text = mTextStorage.getGlyphText(); mLayout = new MongolLayout(text, 0, text.length(), mTextPaint, 0, Gravity.TOP, 1, 0, false, Integer.MAX_VALUE); }
TextRun(int offset, int length, boolean isRotated, boolean isSpanned) { this.offset = offset; this.length = length; this.isRotated = isRotated; TextPaint wp; if (isSpanned) { wp = mWorkPaint; wp.set(mPaint); MetricAffectingSpan[] spans = ((Spanned) mText).getSpans(offset, offset + length, MetricAffectingSpan.class); for(MetricAffectingSpan span : spans) { span.updateDrawState(wp); } } else { wp = mPaint; } // just record the normal non-rotated values here // measure and draw will take rotation into account measuredWidth = wp.measureText(mText, offset, offset + length); measuredHeight = wp.getFontMetrics().bottom - wp.getFontMetrics().top; }
public static Bitmap getOverlayBitmap2(Context context, Bitmap bitmap, String text) { Bitmap result = bitmap.copy(bitmap.getConfig(), true); float scale = context.getResources().getDisplayMetrics().density; Canvas canvas = new Canvas(result); TextPaint mTextPaint = new TextPaint(); mTextPaint.setTextSize((int) (12 * scale)); mTextPaint.setColor(Color.WHITE); mTextPaint.setAlpha(204); mTextPaint.setShadowLayer(5f, 0f, 1f, Color.DKGRAY); StaticLayout mTextLayout = new StaticLayout(text, mTextPaint, canvas.getWidth() - Util.dpToPx(87), Layout.Alignment.ALIGN_CENTER, 1.0f, 0.3f, true); canvas.save(); float textX = (canvas.getWidth() / 2) - (mTextLayout.getWidth() / 2); float textY = result.getHeight() - Util.dpToPx(72); canvas.translate(textX, textY); mTextLayout.draw(canvas); canvas.restore(); return result; }
/** * define paints */ private void initPaint() { // round rectangle paint mStrokePaint = new Paint(); mStrokePaint.setColor(mSelectedColor); mStrokePaint.setStyle(Paint.Style.STROKE); mStrokePaint.setAntiAlias(true); mStrokePaint.setStrokeWidth(mStrokeWidth); // selected paint mFillPaint = new Paint(); mFillPaint.setColor(mSelectedColor); mFillPaint.setStyle(Paint.Style.FILL_AND_STROKE); mStrokePaint.setAntiAlias(true); // selected text paint mSelectedTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); mSelectedTextPaint.setTextSize(mTextSize); mSelectedTextPaint.setColor(mSelectedColor); mStrokePaint.setAntiAlias(true); // unselected text paint mUnselectedTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); mUnselectedTextPaint.setTextSize(mTextSize); mUnselectedTextPaint.setColor(0xffffffff); mStrokePaint.setAntiAlias(true); mTextHeightOffset = -(mSelectedTextPaint.ascent() + mSelectedTextPaint.descent()) * 0.5f; }
private void init() { mTextPaint = new TextPaint(); mTextPaint.setAntiAlias(true); if (mTextSizePx <= 0) { mTextSizePx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, DEFAULT_FONT_SIZE_SP, getResources().getDisplayMetrics()); } mTextPaint.setTextSize(mTextSizePx); mTextPaint.setColor(mTextColor); mTypeface = MongolFont.get(MongolFont.QAGAN, mContext); mTextPaint.setTypeface(mTypeface); mRenderer = MongolCode.INSTANCE; if (mUnicodeText == null) { mUnicodeText = ""; } mGlyphText = mRenderer.unicodeToMenksoft(mUnicodeText); }
@Override protected void onDraw(Canvas canvas){ TextPaint textPaint = getPaint(); textPaint.setColor(getCurrentTextColor()); textPaint.drawableState = getDrawableState(); canvas.save(); if(topDown){ canvas.translate(getWidth(), 0); canvas.rotate(90); }else { canvas.translate(0, getHeight()); canvas.rotate(-90); } canvas.translate(getCompoundPaddingLeft(), getExtendedPaddingTop()); getLayout().draw(canvas); canvas.restore(); }
public AboutLinkCell(Context context) { super(context); textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(AndroidUtilities.dp(16)); textPaint.setColor(0xff000000); textPaint.linkColor = Theme.MSG_LINK_TEXT_COLOR; textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); urlPaint = new Paint(); urlPaint.setColor(Theme.MSG_LINK_SELECT_BACKGROUND_COLOR); urlPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); imageView = new ImageView(context); imageView.setScaleType(ImageView.ScaleType.CENTER); addView(imageView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 0 : 16, 5, LocaleController.isRTL ? 16 : 0, 0)); setWillNotDraw(false); }
/** * 添加指示器 * * @param position * @param title */ private void addTab(final int position, CharSequence title) { TextView tvTab = new TextView(context); tvTab.setText(title); tvTab.setTextColor(textColor); tvTab.setTextSize(textSize); tvTab.setGravity(Gravity.CENTER); if(isIndicatorTextBold){ TextPaint tp = tvTab.getPaint(); tp.setFakeBoldText(true); } tvTab.setSingleLine(); tvTab.setFocusable(true); tvTab.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { viewPager.setCurrentItem(position); } }); tvTab.setPadding(indicatorMargin, 0, indicatorMargin, 0); container.addView(tvTab, position, expandedTabLayoutParams); }
private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { mAttrsHelper.init(context, attrs, defStyleAttr, defStyleRes); setText(mAttrsHelper.mText); TextPaint textPaint = getTextPaint(); textPaint.setColor(mAttrsHelper.mTextColor); textPaint.setTextSize(mAttrsHelper.mTextSize); final Resources.Theme theme = context.getTheme(); TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.FastTextView, defStyleAttr, defStyleRes); mEnableLayoutCache = a.getBoolean(R.styleable.FastTextView_enableLayoutCache, false); a.recycle(); }
/** * Recursive binary search to find the best size for the text. * <p> * Adapted from https://github.com/grantland/android-autofittextview */ public static float getSingleLineTextSize(String text, TextPaint paint, float targetWidth, float low, float high, float precision, DisplayMetrics metrics) { final float mid = (low + high) / 2.0f; paint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, mid, metrics)); final float maxLineWidth = paint.measureText(text); if ((high - low) < precision) { return low; } else if (maxLineWidth > targetWidth) { return getSingleLineTextSize(text, paint, targetWidth, low, mid, precision, metrics); } else if (maxLineWidth < targetWidth) { return getSingleLineTextSize(text, paint, targetWidth, mid, high, precision, metrics); } else { return mid; } }
@Override protected void doBusiness() { SpannableString spannableString = new SpannableString("密码默认为身份证后六位(x小写) 忘记密码?"); spannableString.setSpan(new ClickableSpan() { @Override public void onClick(View widget) { Bundle bundle = new Bundle(); bundle.putInt("type", WebViewActivity.TYPE_CHANGE_PWD); bundle.putString("title", "修改密码"); bundle.putString("url", Constants.CHANGE_PWD); LoginActivity.this.startActivity(WebViewActivity.class, bundle); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(Color.parseColor("#ff8f8f8f")); ds.setUnderlineText(true); } }, 17, 22, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); tvMessage.setText(spannableString); tvMessage.setMovementMethod(LinkMovementMethod.getInstance()); KeyBoardUtils.scrollLayoutAboveKeyBoard(context, rootView, tvMessage); SharedPreferences.Editor editor = getSharedPreferences("login_user", MODE_PRIVATE).edit(); editor.putString("userId", "*"); editor.apply(); loginPresenter = new LoginPresenter(this, this); }
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(); }
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); }
public SpannableBuilder clickable(final CharSequence text, final View.OnClickListener listener) { if (!InputHelper.isEmpty(text)) return append(text, new ClickableSpan() { @Override public void updateDrawState(TextPaint ds) { ds.setColor(ds.linkColor); ds.setUnderlineText(false); } @Override public void onClick(View widget) { listener.onClick(widget); } }); return this; }
protected void initBaseTools() { textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setColor(Color.parseColor("#C1C2C2")); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setStrokeWidth(DIVIDING_LINE_SIZE); }
@Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(mForegroundColor); ds.setUnderlineText(false); ds.bgColor = isBackgroundTransparent ? Color.TRANSPARENT : mBackgroundColor; }
private void measureTabLayoutTextWidth(int position) { String title = titles.get(position); TextView titleView = mSlidingTabLayout.getTitleView(position); TextPaint paint = titleView.getPaint(); float textWidth = paint.measureText(title); mSlidingTabLayout.setIndicatorWidth(textWidth / 3); }
/** * x and y anchored to top-middle point of StaticLayout */ public static void drawLayout(Layout wrappedLabel, float x, float y, Canvas canvas, TextPaint paint) { canvas.save(); canvas.translate(x, y); wrappedLabel.draw(canvas); canvas.restore(); }
/** * get the height which limited line count * * @param typeface * @param maxLineCount * @return */ private int getMaxTextRectHeight(String typeface, int maxLineCount) { TextPaint textPaint = new TextPaint(); textPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, mDefaultMinTextSize, mContext.getResources().getDisplayMetrics())); if (typeface != null) { textPaint.setTypeface(Typeface.createFromAsset(mContext.getAssets(), typeface)); } Paint.FontMetrics fontMetrics = textPaint.getFontMetrics(); int textHeight = (int) Math.ceil(fontMetrics.bottom - fontMetrics.top); return textHeight * maxLineCount + (int) (textHeight * 0.9f) * (maxLineCount - 1); }
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(); }
public Settings(Slidr slidr) { this.slidr = slidr; paintIndicator = new Paint(); paintIndicator.setAntiAlias(true); paintIndicator.setStrokeWidth(2); paintBar = new Paint(); paintBar.setAntiAlias(true); paintBar.setStrokeWidth(2); paintBar.setColor(colorBackground); paintStep = new Paint(); paintStep.setAntiAlias(true); paintStep.setStrokeWidth(5); paintStep.setColor(colorStoppover); paintTextTop = new TextPaint(); paintTextTop.setAntiAlias(true); paintTextTop.setStyle(Paint.Style.FILL); paintTextTop.setColor(textColor); paintTextTop.setTextSize(textTopSize); paintTextBottom = new TextPaint(); paintTextBottom.setAntiAlias(true); paintTextBottom.setStyle(Paint.Style.FILL); paintTextBottom.setColor(textColor); paintTextBottom.setTextSize(textBottomSize); paintBubbleTextCurrent = new TextPaint(); paintBubbleTextCurrent.setAntiAlias(true); paintBubbleTextCurrent.setStyle(Paint.Style.FILL); paintBubbleTextCurrent.setColor(Color.WHITE); paintBubbleTextCurrent.setStrokeWidth(2); paintBubbleTextCurrent.setTextSize(dpToPx(textSizeBubbleCurrent)); paintBubble = new Paint(); paintBubble.setAntiAlias(true); paintBubble.setStrokeWidth(3); }
public boolean checkLayout() { if (type != 0 || messageOwner.to_id == null || messageText == null || messageText.length() == 0) { return false; } if (layoutCreated) { int newMinSize = AndroidUtilities.isTablet() ? AndroidUtilities.getMinTabletSide() : AndroidUtilities.displaySize.x; if (Math.abs(generatedWithMinSize - newMinSize) > AndroidUtilities.dp(52)) { layoutCreated = false; } } if (!layoutCreated) { layoutCreated = true; TLRPC.User fromUser = null; if (isFromUser()) { fromUser = MessagesController.getInstance().getUser(messageOwner.from_id); } TextPaint paint; if (messageOwner.media instanceof TLRPC.TL_messageMediaGame) { paint = gameTextPaint; } else { paint = textPaint; } messageText = Emoji.replaceEmoji(messageText, paint.getFontMetricsInt(), AndroidUtilities.dp(20), false); generateLayout(fromUser); return true; } return false; }
/** 获取字符串宽度 */ public static float GetTextWidth(String Sentence, float Size) { if (isEmpty(Sentence)) return 0; TextPaint FontPaint = new TextPaint(); FontPaint.setTextSize(Size); return FontPaint.measureText(Sentence.trim()) + (int) (Size * 0.1); // 留点余地 }
@Override public void updateDrawState(TextPaint tp) { tp.setTypeface(mTypeface); // Note: This flag is required for proper typeface rendering tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG); }
@Override public void updateDrawState(TextPaint ds) { ds.setUnderlineText(false); //给标记的部分 的文字 添加颜色 if(clickString.equals("toName")){ ds.setColor(context.getResources().getColor(R.color.colorPrimary)); }else if(clickString.equals("name")){ ds.setColor(context.getResources().getColor(R.color.colorPrimary)); } }
private TextPaint textPaint() { final TextPaint paint = new TextPaint(); paint.setColor(Color.BLACK); paint.setAntiAlias(true); paint.setTextSize(24); paint.setTextAlign(Paint.Align.CENTER); return paint; }
private int getTextOffsetX(TextPaint paint, String s, int gravity) { int width = (int) paint.measureText(s); int offset = 0; if ((gravity & Gravity.CENTER_HORIZONTAL) != 0) { offset = - width / 2; } else if ((gravity & Gravity.START) != 0) { offset = - width; } return offset; }
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(); }
public void measureTabLayoutTextWidth(int position) { String titleName = titles.get(position); TextView titleView = mSlidingTab.getTitleView(position); TextPaint paint = titleView.getPaint(); float v = paint.measureText(titleName); mSlidingTab.setIndicatorWidth(v / 3); }
@Override public void updateDrawState(TextPaint ds) { apply(ds); if (!multiline) { ds.bgColor = theme.getCodeBackgroundColor(ds); } }
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); //首先进行高度调整 if (firstCalc) { width = getMeasuredWidth(); String text = getText().toString(); TextPaint paint = getPaint(); lines.clear(); tailLines.clear(); // 文本含有换行符时,分割单独处理 String[] items = text.split("\\n"); for (String item : items) { calc(paint, item); } //使用替代textview计算原始高度与行数 measureTextViewHeight(text, paint.getTextSize(), getMeasuredWidth() - getPaddingLeft() - getPaddingRight()); //获取行高 textHeight = 1.0f * originalHeight / originalLineCount; textLineSpaceExtra = textHeight * (lineSpacingMultiplier - 1) + lineSpacingAdd; //计算实际高度,加上多出的行的高度(一般是减少) int heightGap = (int) ((textLineSpaceExtra + textHeight) * (lines.size() - originalLineCount)); setPaddingFromMe = true; //调整textview的paddingBottom来缩小底部空白 setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), originalPaddingBottom + heightGap); firstCalc = false; } }
private int getTextOffsetY(TextPaint paint, int gravity) { int height = (int) (paint.getFontMetrics().descent - paint.getFontMetrics().ascent); int offset = (int) (paint.getFontMetrics().descent + paint.getFontMetrics().ascent) / 2; if ((gravity & Gravity.CENTER_VERTICAL) != 0) { offset += height / 2; } else if ((gravity & Gravity.BOTTOM) != 0) { offset += height; } return offset; }