/
Practice12MeasureTextView.java
49 lines (39 loc) · 1.47 KB
/
Practice12MeasureTextView.java
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
package com.geekholt.practiceui.view.lesson3;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import androidx.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class Practice12MeasureTextView extends View {
Paint paint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint paint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
String text1 = "三个月内你胖了";
String text2 = "4.5";
String text3 = "公斤";
public Practice12MeasureTextView(Context context) {
super(context);
}
public Practice12MeasureTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public Practice12MeasureTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
paint1.setTextSize(60);
paint2.setTextSize(120);
paint2.setColor(Color.parseColor("#E91E63"));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 使用 Paint.measureText 测量出文字宽度,让文字可以相邻绘制
canvas.drawText(text1, 50, 200, paint1);
float text1Width = paint1.measureText(text1);
canvas.drawText(text2, 50 + text1Width, 200, paint2);
float text2Width = paint2.measureText(text2);
canvas.drawText(text3, 50 + text1Width + text2Width, 200, paint1);
}
}