textview带有右上角文字

rightuptext pic

1.RightUpperCornerText 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
public class RightUpperCornerText extends TextView {
private Paint mPaint;
private String mCornerText;
private Context mContext;
public RightUpperCornerText(Context context) {
super(context);
init(context);
}
public RightUpperCornerText(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RightUpperCornerText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
mContext = context;
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.WHITE);
float cornerSize = getTextSize() * 0.6f;
if (cornerSize > 50) {
cornerSize = 50;
}
mPaint.setTextSize(cornerSize);
mCornerText = "";
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 不要忘了设置 Padding
String text = (String) getText();
Rect bounds = new Rect();
getPaint().getTextBounds(text, 0, text.length(), bounds);
canvas.drawText(mCornerText, getPaddingLeft() + bounds.right + bounds.left,
(canvas.getHeight() + bounds.top) / 2 + mPaint.measureText(mCornerText),
mPaint);
}
public void setCornertext(String text) {
mCornerText = text;
}
public void setCornertextSize(float size) {
mPaint.setTextSize(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
size, mContext.getResources().getDisplayMetrics()));
invalidate();
}
}

2. 用法

1
2
3
4
5
6
7
8
<com.ilegendsoft.toprankapps.cleanmaster.UI.RightUpperCornerText
android:id="@+id/dashboard_percentage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:layout_centerInParent="true"
android:textColor="@android:color/white"
android:textSize="26sp" />

mPercentageView.setCornertext(cornerText);

注意 android:padding="20dp"设置padding 很重要,否则没地方画了。

3. 其实完全没必要自定义,采用TextView Style可以实现各种样式的字体排版,就是SpannableString

先看下图片

复合文本图片

具体参考如下链接: