Raf*_*afe 2 .net graphics text gdi
我目前正在使用.Net中的System.Drawing.Graphics.DrawString()方法在图像上绘制文本,然后将其保存到新文件:
// define image file paths
string sourceImagePath = HttpContext.Current.Server.MapPath("~/img/sourceImage.jpg");
string destinationImagePath = HttpContext.Current.Server.MapPath("~/img/") + "finalImage.jpg";
// create new graphic to draw to
Bitmap bm = new Bitmap(200, 200);
Graphics gr = Graphics.FromImage(bm);
// open and draw image into new graphic
System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sourceImagePath, true);
gr.DrawImage(sourceImage, 0, 0);
sourceImage.Dispose();
// write "my text" on center of image
gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
PrivateFontCollection fontCollection = new PrivateFontCollection();
fontCollection.AddFontFile(HttpContext.Current.Server.MapPath("~/fonts/HelveticaNeueLTStd-BlkCn.ttf"));
// prototype (1)
gr.DrawString("my text", new Font(fontCollection.Families[0], 14, FontStyle.Bold), new SolidBrush(Color.FromArgb(255, 255, 255)), 100, 0, sf);
fontCollection.Dispose();
// save new image
if (File.Exists(destinationImagePath))
{
File.Delete(destinationImagePath);
}
bm.Save(destinationImagePath);
bm.Dispose();
gr.Dispose();
Run Code Online (Sandbox Code Playgroud)
这种在图像上添加文本的方法并没有提供一种向文本添加笔划的方法(我知道).例如,我真正需要做的是为图像上写入的文本添加一定颜色的2px笔划.
如何使用.Net Framework <= v3.5完成此操作?
所有文字都有笔画.
如果你用笔画表示轮廓,那么你创建一个GraphicsPath并使用添加字符串AddString,然后你可以使用DrawPath而不是FillPath在msdn上的例子中使用它来勾画路径.
private void Form1_Paint(object sender, PaintEventArgs e)
{
// Create a GraphicsPath object.
GraphicsPath myPath = new GraphicsPath();
// Set up all the string parameters.
string stringText = "Sample Text";
FontFamily family = new FontFamily("Arial");
int fontStyle = (int)FontStyle.Italic;
int emSize = 96;
Point origin = new Point(20, 20);
StringFormat format = StringFormat.GenericDefault;
// Add the string to the path.
myPath.AddString(stringText,
family,
fontStyle,
emSize,
origin,
format);
//Draw the path to the screen.
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
e.Graphics.FillPath(Brushes.BlanchedAlmond, myPath);
e.Graphics.DrawPath(new Pen(Brushes.Azure, 2), myPath);
}
Run Code Online (Sandbox Code Playgroud)
如果按笔划表示serif,则使用不同的字体.
| 归档时间: |
|
| 查看次数: |
3525 次 |
| 最近记录: |