110,502
社区成员
发帖
与我相关
我的任务
分享
var 颜色 = (单元序号++ == 高亮点 % 文本.Count) ? Brushes.Red : Brushes.Black;
Winform做“居中对齐”很容易,但不容易做“两端对齐”。换WPF会好做一些。
在Winform下,两端对齐还要自己做,同样是测量每个字母,然后计算排版。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Width = 300;
this.DoubleBuffered = true;
this.Font = new Font("宋体", 14);
this.SizeChanged += delegate { Invalidate(); };
this.定时器.Tick += delegate { this.高亮点++; Invalidate(); };
}
protected override void OnPaint(PaintEventArgs e)
{
const float 行距 = 4;
const float 间距 = 4;
var 行高 = e.Graphics.MeasureString("字", this.Font).Height;
float 当前x = 0, 当前y = 0;
var 单元序号 = 0;
foreach(var 单元 in 文本)
{
var 拼音宽 = e.Graphics.MeasureString(单元.拼音 ?? "", this.Font).Width;
var 词组宽 = e.Graphics.MeasureString(单元.词组 ?? "", this.Font).Width;
var 单位宽 = Math.Max(拼音宽, 词组宽);
if (当前x + 单位宽 > this.ClientSize.Width)
{
当前x = 0;
当前y += 行高 + 行高 + 行距;
}
var 拼音框 = new RectangleF(当前x, 当前y, 单位宽, 行高);
var 词组框 = new RectangleF(当前x, 当前y + 行高, 单位宽, 行高);
var 颜色 = (单元序号++ % 文本.Count == 高亮点) ? Brushes.Red : Brushes.Black;
e.Graphics.DrawString(单元.拼音 ?? "", this.Font, 颜色, 拼音框, 居中格式);
e.Graphics.DrawString(单元.词组 ?? "", this.Font, 颜色, 词组框, 居中格式);
当前x += 单位宽 + 间距;
}
}
int 高亮点 = 0;
Timer 定时器 = new Timer() { Interval = 500, Enabled = true};
static StringFormat 居中格式 = new StringFormat() {Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center};
List<注音词组> 文本 = new List<注音词组>()
{
new 注音词组("Qīngzǎo", "清早"),
new 注音词组("", ","),
new 注音词组("wǒ", "我"),
new 注音词组("zǒu", "走"),
new 注音词组("zài", "在"),
new 注音词组("héngkuà", "横跨"),
new 注音词组("hé'àn", "河岸"),
new 注音词组("hé", "和"),
new 注音词组("xiǎodǎo", "小岛"),
new 注音词组("chǎngchǎng", "长长"),
new 注音词组("de", "的"),
new 注音词组("dúmùqiáo", "独木桥"),
new 注音词组("shàng", "上"),
new 注音词组("", ","),
new 注音词组("shǒulǐ", "手里"),
new 注音词组("zhuāizhe", "拽着"),
new 注音词组("niúshéng", "牛绳"),
new 注音词组("", "。"),
};
}
struct 注音词组
{
public 注音词组(string p, string c)
{
拼音 = p;
词组 = c;
}
public string 拼音;
public string 词组;
}