Drawing text on image

可紊 提交于 2019-12-19 19:56:41

问题


I have never worked with drawing before and im having a little issue. I cant seem to get the output of this code to work.

The file is saving but it is not drawing on the text. Can anyone see what i may have done wrong?

EDIT: A silly mistake - the backgrond of the image was white (and the brush colour was!). The text is not centered however as i would have expected. Any ideas why SO? :)

EDIT: Image is below.

Thanks

Bitmap myBitmap = new Bitmap(@"C:\Users\Scott\desktop\blank.bmp");
Graphics g = Graphics.FromImage(myBitmap);

g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
g.DrawString("My\nText", 
             new Font("Tahoma", 20), 
             Brushes.White, 
             new PointF(0, 0));

StringFormat strFormat = new StringFormat();
strFormat.Alignment = StringAlignment.Center;
strFormat.LineAlignment = StringAlignment.Center;

g.DrawString("My\nText", 
             new Font("Tahoma", 20), Brushes.White, 
             new RectangleF(0, 0, 500, 500), 
             strFormat);
myBitmap.Save(@"C:\Users\Scott\desktop\blank1.bmp");

回答1:


I am sure you might be looking for this.

rectf = new RectangleF(655, 460, 535, 90); //rectf for My Text
using(Graphics g = Graphics.FromImage(myBitmap))
{
    //g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90); 
    g.SmoothingMode = SmoothingMode.AntiAlias;
    g.InterpolationMode = InterpolationMode.HighQualityBicubic;
    g.PixelOffsetMode = PixelOffsetMode.HighQuality;
    StringFormat sf = new StringFormat();
    sf.Alignment = StringAlignment.Center;
    sf.LineAlignment = StringAlignment.Center;
    g.DrawString("My\nText", new System.Drawing.Font("Tahoma", 32, FontStyle.Bold), Brushes.Black, rectf, sf);
}

//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90); Line is used to show where your text will be written. So before you actually make your make your text You can see where this rectanlge will be created on the image. If you want the center of the image you can find the height and width and divide that by 2 to find the center of the image and than can plot the rectangle parameters accordingly.



来源:https://stackoverflow.com/questions/17192431/drawing-text-on-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!