求助高手!一个电子印章生成算法的问题
各位大哥,小弟最近在做一个印章程序,能根据你输入的文字,生成一个印章图片,并可以对图片进行保存。现在的最关键的问题是输入的文字如何排列在印章上,希望能知道有关对文字进行旋转和排列的算法或计算方法。没有语言显示,主要是想知道相关的算法。希望各位大哥出手相助。
[解决办法]
public void RenderSeal(Graphics g, string text, PointF center, float radius, float angle)
{
float newAngle = (angle % 360 - 180) / 2 + 180;
int times = text.Length;
SizeF sf = SizeF.Empty;
Font font = new Font("仿宋", 20f);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
sf = g.MeasureString(text[0].ToString(), font);
//外圆
g.DrawEllipse(new Pen(Color.Red, 5),
new RectangleF(center.X - radius - sf.Width / 2,
center.Y - radius - sf.Width / 2, radius * 2 + sf.Width, radius * 2 + sf.Height));
//绘制印章文字
for (int i = 0; i < times; i++)
{
float tempAngle = (newAngle - i * (angle / (times - 1)));
float x = (float)Math.Cos((-1) * tempAngle * Math.PI / 180) * radius + center.X;
float y = (float)Math.Sin((-1) * tempAngle * Math.PI / 180) * radius + center.Y;
//先平移再旋转
g.ResetTransform();
g.TranslateTransform(x, y);
g.RotateTransform(90 - tempAngle);
sf = g.MeasureString(text[i].ToString(), font);
g.DrawString(text[i].ToString(), font, Brushes.Red, -sf.Width / 2, -sf.Height / 2);
}
}
Paint:
Graphics g = e.Graphics;
RenderSeal(g, "一个电子印章生成算法", new PointF(ClientRectangle.Width / 2, ClientRectangle.Height / 2), 80, 240);
实现思路主要是根据印章文字计算每个字体的偏移角度,求出它的偏移位置进行平移,再根据相应的角度进行旋转,注意的地方就是GDI+坐标与笛卡尔坐标不一样,旋转的时候就要转换一下
//上面是绘制印章的算法,这里是绘制五角星的,参数信息为:
//g:绘图表面
//pt:绘制位置
//radius:外接五角星圆的半径(决定五角星大小)
//angle:旋转角度
public void RenderStar(Graphics g, PointF pt, float radius, float angle = 0)
{
int[] pointSequence = { 2, 4, 1, 3, 0 };
List<PointF> points = new List<PointF>(pointSequence.Length);
for (int i = 0; i < pointSequence.Length; i++)
{
float radian = (54 + 72 * pointSequence[i]) * (float)Math.PI / 180;
points.Add(new PointF((float)Math.Cos(radian) * radius, (float)Math.Sin(radian) * radius));
}
g.ResetTransform();
g.TranslateTransform(pt.X, pt.Y);
g.RotateTransform(angle);
g.FillPolygon(Brushes.Red, points.ToArray(), System.Drawing.Drawing2D.FillMode.Winding);
}