/
Practice14GetFontMetricsView.java
59 lines (48 loc) · 2.03 KB
/
Practice14GetFontMetricsView.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
50
51
52
53
54
55
56
57
58
59
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 Practice14GetFontMetricsView extends View {
Paint paint1 = new Paint(Paint.ANTI_ALIAS_FLAG);
Paint paint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
String[] texts = {"A", "a", "J", "j", "Â", "â"};
float yOffset;
int top = 200;
int bottom = 400;
public Practice14GetFontMetricsView(Context context) {
super(context);
}
public Practice14GetFontMetricsView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public Practice14GetFontMetricsView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
paint1.setStyle(Paint.Style.STROKE);
paint1.setStrokeWidth(20);
paint1.setColor(Color.parseColor("#E91E63"));
paint2.setTextSize(160);
Paint.FontMetrics fontMetrics = paint2.getFontMetrics();
yOffset = - (fontMetrics.ascent + fontMetrics.descent) / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(50, top, getWidth() - 50, bottom, paint1);
// 使用 Paint.getFontMetrics() 计算出文字的显示区域
// 然后计算出文字的绘制位置,从而让文字上下居中
// 这种居中算法的优点是,可以让不同的文字的 baseline 对齐
int middle = (top + bottom) / 2;
canvas.drawText(texts[0], 100, middle + yOffset, paint2);
canvas.drawText(texts[1], 200, middle + yOffset, paint2);
canvas.drawText(texts[2], 300, middle + yOffset, paint2);
canvas.drawText(texts[3], 400, middle + yOffset, paint2);
canvas.drawText(texts[4], 500, middle + yOffset, paint2);
canvas.drawText(texts[5], 600, middle + yOffset, paint2);
}
}