日期:2014-05-18  浏览次数:20830 次

请问用drawstring如何找到文字中心?
首先问大家个问题,大家现在在程序中画图形和文字还是使用graphic里面的drawstring drawline这些函数吗?
感觉不是很方便

正题:
我现在想实现,在picturebox上画很多圆,每个圆的中心写文字,为了对齐,最好的办法就是找到他们的中心吧
怎么实现现在还没有想好,希望有人可以指点一下。

------解决方案--------------------
Point center; // 圆心
int radius; // 半径
bool dragging; // 是否画图中

private void PictureBox_Paint(object sender, PaintEventArgs e)
{
Rectangle rect = new Rectangle(center, Size.Empty);
rect.Inflate(radius, radius);
e.Graphics.DrawEllipse(Pens.DarkCyan, rect);
}

private void PictureBox_MouseDown(object sender, MouseEventArgs e)
{
center = e.Location;
radius = 0;
dragging = true;
}

private void PictureBox_MouseMove(object sender, MouseEventArgs e)
{
if (dragging)
{
Point diff = new Point(e.Location.X - center.X, e.Location.Y - center.Y);
radius = (int)Math.Sqrt(diff.X * diff.X + diff.Y * diff.Y);
PictureBox.Invalidate();
}
}

private void PictureBox_MouseUp(object sender, MouseEventArgs e)
{
dragging = false;
PictureBox.Invalidate();

}

private void Form1_Load(object sender, EventArgs e)
{
this.pictureBox1.MouseDown += PictureBox_MouseDown;
this.pictureBox1.MouseMove += PictureBox_MouseMove;
this.pictureBox1.MouseUp += PictureBox_MouseUp;
}

------解决方案--------------------
画圆的时候不是有圆点么
------解决方案--------------------
Graphics.DrawString可以传入一个StringFormat参数用来控制文字在矩形框中的位置:

C# code

StringFormat sf = new StringFormat()
{
    Alignment = StringAlignment.Center,
    LineAlignment = StringAlignment.Center,
};
Rectangle layoutRectange = ...;
graphics.DrawString("sdf", this.Font, Brushes.Black, layoutRectange, sf);