下面列出了怎么用android.text.TextPaint的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void updateDrawState(TextPaint tp) {
switch (mTextDecoration) {
case LINETHROUGH:
tp.setUnderlineText(false);
tp.setStrikeThruText(true);
break;
case UNDERLINE:
tp.setUnderlineText(true);
tp.setStrikeThruText(false);
break;
case NONE:
tp.setUnderlineText(false);
tp.setStrikeThruText(false);
break;
}
}
private void init() {
setMovementMethod(LinkMovementMethod.getInstance());
ClickableSpan clickable = new ClickableSpan() {
@Override
public void updateDrawState(@NonNull TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setColor(ThemeUtil.getThemedColor(getContext(), R.attr.colorAccent));
}
@Override
public void onClick(@NonNull View widget) {
if (linkListener != null) {
linkListener.onClick(widget);
}
}
};
link = new SpannableString(getContext().getString(R.string.LearnMoreTextView_learn_more));
link.setSpan(clickable, 0, link.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
visible = true;
}
@Override
public void init(Service service) {
this.background = service.getResources().getColor(R.color.malvarez_background);
this.leftFuzzyText = 160;
this.textFont = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
this.textFont.setTypeface(ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE));
this.textFont.setTextSize(service.getResources().getDimension(R.dimen.drbourbon_fuzzytext_font_size));
this.textFont.setColor(service.getResources().getColor(R.color.malvarez_time_colour));
this.textFont.setTextAlign(Paint.Align.CENTER);
hours = service.getResources().getStringArray(R.array.hours);
phrases = service.getResources().getStringArray(R.array.phrases);
digits = service.getResources().getStringArray(R.array.digits);
Rect bounds = new Rect();
String sampleTime = "12:58";
textFont.getTextBounds(sampleTime, 0, sampleTime.length(), bounds);
this.fontHeight = bounds.height();
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text,
int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
boolean isLeftEdge = x == 0.0f;
if (backgroundColor != 0) {
int extra1Dp = (int) (((TextPaint) paint).density * 1 + 0.5f);
float width = paint.measureText(text.subSequence(start, end).toString());
int newTop = (int) (bottom - paint.getFontSpacing() - paint.descent()) + 2 * extra1Dp;
int newBottom = bottom - extra1Dp;
int newLeft = (int) (isLeftEdge ? x : x - radius);
int newRight = (int) (isLeftEdge ? x + width + 2 * radius : x + width + radius);
RectF rect = new RectF(newLeft, newTop, newRight, newBottom);
paint.setColor(backgroundColor);
canvas.drawRoundRect(rect, radius, radius, paint);
}
if (textColor != 0) {
float textX = isLeftEdge ? x + radius : x;
paint.setColor(textColor);
canvas.drawText(text, start, end, textX, y, paint);
}
}
private void init() {
setContentView(R.layout.dialog_confirm);
this.mTitleView = (TextView) findViewById(R.id.title);
final TextPaint tp = this.mTitleView.getPaint();
tp.setFakeBoldText(true);
this.mTitleView.setText(this.mTitle);
this.mTextView = (TextView) findViewById(R.id.text);
this.mTextView.setText(this.mText);
this.mButton1 = (Button) findViewById(R.id.button1);
this.mButton1.setOnClickListener(this);
this.mButton2 = (Button) findViewById(R.id.button2);
this.mButton2.setOnClickListener(this);
}
private SpannableString getEmailVerficationSpannableString() {
String str1 = this.mContext.getString(R.string.login_email_send_hint1);
String str2 = this.mContext.getString(R.string.login_send_email_hint2);
SpannableString spannableString = new SpannableString(str1 + str2);
spannableString.setSpan(new ForegroundColorSpan(this.mContext.getResources().getColor(R.color.register_agreement)), 0, str1.length(), 33);
spannableString.setSpan(new ForegroundColorSpan(this.mContext.getResources().getColor(R.color.register_agreement)), str1.length() + str2.length(), str1.length() + str2.length(), 33);
spannableString.setSpan(new ClickableSpan() {
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(ForgetIphonePasswordFragment.this.getResources().getColor(R.color.register_agreement_click));
ds.setUnderlineText(false);
}
public void onClick(View widget) {
}
}, str1.length(), str1.length() + str2.length(), 33);
return spannableString;
}
public void applyStyle(TextPaint p) {
Typeface typeface = getTypeface();
if (typeface != null) {
p.setTypeface(typeface);
}
if ((flags & FLAG_STYLE_UNDERLINE) != 0) {
p.setFlags(p.getFlags() | Paint.UNDERLINE_TEXT_FLAG);
} else {
p.setFlags(p.getFlags() &~ Paint.UNDERLINE_TEXT_FLAG);
}
if ((flags & FLAG_STYLE_STRIKE) != 0) {
p.setFlags(p.getFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
p.setFlags(p.getFlags() &~ Paint.STRIKE_THRU_TEXT_FLAG);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
getActivity().setTheme(R.style.DayTheme);
if (MyApplication.nightMode2()) {
initNightView(R.layout.night_mode_overlay);
}
View view = inflater.inflate(R.layout.fragment_about, container, false);
TextView tv = (TextView) view.findViewById(R.id.link);
String textStr = "https://github.com/byhieg/easyweather";
tv.setAutoLinkMask(Linkify.WEB_URLS);
tv.setText(textStr);
Spannable s = (Spannable) tv.getText();
s.setSpan(new UnderlineSpan() {
@Override
public void updateDrawState(TextPaint ds) {
ds.setColor(ds.linkColor);
ds.setUnderlineText(false);
}
}, 0, textStr.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return view;
}
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;
}
TextView getTextView() {
//设置TextView的样式
AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, 64);
TextView textView = new TextView(
mContext);
textView.setLayoutParams(lp);
textView.setGravity(Gravity.CENTER_VERTICAL);
//设置TextView的Padding值
textView.setPadding(16, -10, 0, 32);
//设置TextView的字体大小
textView.setTextSize(14);
//设置TextView的字体颜色
textView.setTextColor(Color.WHITE);
//设置字体加粗
TextPaint txt = textView.getPaint();
txt.setFakeBoldText(true);
return textView;
}
private SpannableString getDescriptionText() {
return SpanApplier.applySpans(
getString(R.string.physical_web_optin_description),
new SpanInfo("<learnmore>", "</learnmore>", new ClickableSpan() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(PHYSICAL_WEB_LEARN_MORE_URL));
// Add the SESSION extra to indicate we want a Chrome custom tab. This
// allows the help page to open in the same task as the opt-in activity so
// they can share a back stack.
String session = null;
intent.putExtra(EXTRA_CUSTOM_TABS_SESSION, session);
PhysicalWebOptInActivity.this.startActivity(intent);
}
@Override
public void updateDrawState(TextPaint ds) {
// Color links but do not underline them.
ds.setColor(ds.linkColor);
}
}));
}
public WallpaperCheckBoxView(Context context, boolean check) {
super(context);
rect = new RectF();
if (check) {
drawBitmap = Bitmap.createBitmap(AndroidUtilities.dp(18), AndroidUtilities.dp(18), Bitmap.Config.ARGB_4444);
drawCanvas = new Canvas(drawBitmap);
}
textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(AndroidUtilities.dp(14));
textPaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
checkPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
checkPaint.setStyle(Paint.Style.STROKE);
checkPaint.setStrokeWidth(AndroidUtilities.dp(2));
checkPaint.setColor(0);
checkPaint.setStrokeCap(Paint.Cap.ROUND);
checkPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
eraserPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
eraserPaint.setColor(0);
eraserPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
backgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
}
private IconDrawable(Context context, @NonNull IconState state) {
iconState = state;
paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
// We have already confirmed that a typeface exists for this icon during
// validation, so we can ignore the null pointer warning.
//noinspection ConstantConditions
paint.setTypeface(Iconify.findTypefaceOf(state.icon).getTypeface(context));
paint.setStyle(state.style);
paint.setTextAlign(Paint.Align.CENTER);
paint.setUnderlineText(false);
color = state.colorStateList.getColorForState(StateSet.WILD_CARD, DEFAULT_COLOR);
paint.setColor(color);
updateTintFilter();
setModulatedAlpha();
paint.setDither(iconState.dither);
text = String.valueOf(iconState.icon.character());
if (SDK_INT < LOLLIPOP && iconState.bounds != null) {
setBounds(iconState.bounds);
}
}
public void applyStyle(TextPaint p) {
Typeface typeface = getTypeface();
if (typeface != null) {
p.setTypeface(typeface);
}
if ((flags & FLAG_STYLE_UNDERLINE) != 0) {
p.setFlags(p.getFlags() | Paint.UNDERLINE_TEXT_FLAG);
} else {
p.setFlags(p.getFlags() &~ Paint.UNDERLINE_TEXT_FLAG);
}
if ((flags & FLAG_STYLE_STRIKE) != 0) {
p.setFlags(p.getFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
} else {
p.setFlags(p.getFlags() &~ Paint.STRIKE_THRU_TEXT_FLAG);
}
}
@Override
public void updateDrawState(TextPaint tp) {
if (color != AttrParser.COLOR_NONE) {
tp.setColor(color);
}
// if (bgClolr >= 0) {
// tp.bgColor = bgClolr;
// }
if (fontSize > 0) {
if (fontSize > TEXT_SIZE.length) {
fontSize = TEXT_SIZE.length;
}
tp.setTextSize(tp.getTextSize() * TEXT_SIZE[fontSize - 1]);
}
}
@Override
public void updateDrawState(TextPaint tp) {
if (typeface != null) {
tp.setTypeface(typeface);
}
if (textSize != 0) {
tp.setTextSize(textSize);
}
if (color != 0) {
tp.setColor(color);
}
tp.setFlags(tp.getFlags() | Paint.SUBPIXEL_TEXT_FLAG);
}
/** Create a new paint after the builder builds for the first time. */
void createNewPaintIfNeeded() {
// Once after build() is called, it is not safe to set properties
// on the paint as we cache the text layouts.
// Hence we create a new paint object,
// if we ever change one of the paint's properties.
if (mForceNewPaint) {
TextPaint newPaint = new TextPaint(paint);
newPaint.set(paint);
paint = newPaint;
mForceNewPaint = false;
}
}
public static Bitmap getAlphabetImage(Context context, String content) {
Resources res = context.getResources();
Bitmap mDefaultBitmap = BitmapFactory.decodeResource(res, android.R.drawable.sym_def_app_icon);
int width = mDefaultBitmap.getWidth();
int height = mDefaultBitmap.getHeight();
TextPaint mPaint = new TextPaint();
mPaint.setTypeface(OControlHelper.boldFont());
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setAntiAlias(true);
int textSize = res.getDimensionPixelSize(R.dimen.text_size_xxlarge);
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas();
Rect mBounds = new Rect();
canvas.setBitmap(bitmap);
canvas.drawColor(OStringColorUtil.getStringColor(context, content));
if (content == null || content.trim().length() == 0) {
content = "?";
}
char[] alphabet = {Character.toUpperCase(content.trim().charAt(0))};
mPaint.setTextSize(textSize);
mPaint.getTextBounds(alphabet, 0, 1, mBounds);
canvas.drawText(alphabet, 0, 1, 0 + width / 2,
0 + height / 2 + (mBounds.bottom - mBounds.top) / 2, mPaint);
return bitmap;
}
public AvatarDrawable() {
super();
namePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
namePaint.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf"));
namePaint.setTextSize(AndroidUtilities.dp(18));
}
@Override
public void updateDrawState(TextPaint p) {
int color = p.getColor();
super.updateDrawState(p);
if (style != null) {
style.applyStyle(p);
p.setUnderlineText(p.linkColor == color);
}
}
/**
* Change the style of the object: blue and not underline
*
* @param ds TextPaint with the style of the object
*/
public void updateDrawState(TextPaint ds) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
ds.setColor(getResources().getColor(R.color.colorAccent, null));// Set text color
} else {
ds.setColor(getResources().getColor(R.color.colorAccent));// Set text color
}
ds.setUnderlineText(false); // Set to false to remove underline
}
@Override
public void updateDrawState(TextPaint ds) {
if (type != 2) {
ds.setColor(context.getResources().getColor(R.color.text_color));
}
ds.setUnderlineText(false); // 去掉下划线
}
private void translateText(Layout layout, BufferType type) {
originalLineCount = layout.getLineCount();
if (layout.getLineCount() > mShowMaxLine) {
isOverMaxLine = true;
SpannableStringBuilder span = new SpannableStringBuilder();
int start = layout.getLineStart(mShowMaxLine - 1);
int end = layout.getLineEnd(mShowMaxLine - 1);
if (mTipGravity == END) {
TextPaint paint = getPaint();
StringBuilder builder = new StringBuilder(ELLIPSIZE_END).append(mFoldText);
end -= paint.breakText(mOriginalText, start, end, false, paint.measureText(builder.toString()), null);
float x = getWidth() - getPaddingLeft() - getPaddingRight() - getTextWidth(mFoldText);
while (layout.getPrimaryHorizontal(end - 1) + getTextWidth(mOriginalText.subSequence(end - 1, end).toString()) < x) {
end++;
}
end--;
} else {
end--;
}
CharSequence ellipsize = mOriginalText.subSequence(0, end);
span.append(ellipsize);
span.append(ELLIPSIZE_END);
if (mTipGravity != END) {
span.append("\n");
}
super.setText(span, type);
} else {
isOverMaxLine = false;
}
}
public void drawText(BaseDanmaku danmaku, String lineText, Canvas canvas, float left, float top, TextPaint paint, boolean fromWorkerThread) {
if (lineText != null) {
canvas.drawText(lineText, left, top, paint);
} else {
canvas.drawText(danmaku.text.toString(), left, top, paint);
}
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
if (currentType == 2) {
ds.setColor(0xffffffff);
} else if (currentType == 1) {
ds.setColor(Theme.getColor(Theme.key_chat_messageLinkOut));
} else {
ds.setColor(Theme.getColor(Theme.key_chat_messageLinkIn));
}
ds.setUnderlineText(false);
}
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();
}
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;
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
if (currentType == 2) {
ds.setColor(0xffffffff);
} else if (currentType == 1) {
ds.setColor(Theme.getColor(enabled ? Theme.key_chat_messageLinkOut : Theme.key_chat_messageTextOut));
} else {
ds.setColor(Theme.getColor(enabled ? Theme.key_chat_messageLinkIn : Theme.key_chat_messageTextIn));
}
ds.setUnderlineText(false);
}
private void init() {
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mBadgeTextRect = new RectF();
mBadgeBackgroundRect = new RectF();
mDragPath = new Path();
mBadgeCenter = new PointF();
mDragCenter = new PointF();
mRowBadgeCenter = new PointF();
mControlPoint = new PointF();
mInnertangentPoints = new ArrayList<>();
mBadgeTextPaint = new TextPaint();
mBadgeTextPaint.setAntiAlias(true);
mBadgeTextPaint.setSubpixelText(true);
mBadgeTextPaint.setFakeBoldText(true);
mBadgeTextPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
mBadgeBackgroundPaint = new Paint();
mBadgeBackgroundPaint.setAntiAlias(true);
mBadgeBackgroundPaint.setStyle(Paint.Style.FILL);
mBadgeBackgroundBorderPaint = new Paint();
mBadgeBackgroundBorderPaint.setAntiAlias(true);
mBadgeBackgroundBorderPaint.setStyle(Paint.Style.STROKE);
mColorBackground = 0xFFE84E40;
mColorBadgeText = 0xFFFFFFFF;
mBadgeTextSize = DisplayUtil.dp2px(getContext(), 11);
mBadgePadding = DisplayUtil.dp2px(getContext(), 5);
mBadgeNumber = 0;
mBadgeGravity = Gravity.END | Gravity.TOP;
mGravityOffsetX = DisplayUtil.dp2px(getContext(), 1);
mGravityOffsetY = DisplayUtil.dp2px(getContext(), 1);
mFinalDragDistance = DisplayUtil.dp2px(getContext(), 90);
mShowShadow = true;
mDrawableBackgroundClip = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setTranslationZ(1000);
}
}
public FloatingLabelSpinner(Context context, AttributeSet attrs, int defStyleAttr, int mode) {
super(context, attrs, defStyleAttr, mode);
final int anti_alias_flag = Paint.ANTI_ALIAS_FLAG;
labelPaint = new TextPaint(anti_alias_flag);
dividerPaint = new Paint(anti_alias_flag);
iconPaint = new Paint(anti_alias_flag);
errorPaint = new TextPaint(anti_alias_flag);
touch_slop = (short) ViewConfiguration.get(context).getScaledTouchSlop();
init(context, attrs);
}