我从指定的文本生成图像,但是删除生成的图像顶部和底部的填充存在一些问题。
我尝试通过使用DrawString更改字符串格式,但是以某种方式实现了从左侧和右侧删除的操作。
#define MAX_VALUE_FOR_ARRAYS 1000
int main()
{
long pos = 0; /// this will store the position of the cursor
char address_book_content[MAX_VALUE_FOR_ARRAYS];
char contact_name[MAX_VALUE_FOR_ARRAYS];
char *string_exists = NULL;
File *show_address_book = NULL;
show_address_book = fopen("addressBook.txt", "r");
printf("Enter the name of the contact you want to search");
scanf("%s", &contact_name);
/** I want : when the user inputs a name, the program searches it in the file and if it’s found it prints the rest of the file starting from the line where that name is. So I tried the following **/
while ( (fgets(address_book_content, MAX_VALUE_FOR_ARRAYS, show_address_book) != NULL)
{
if ( (string_exists = strstr(address_book_content, contact_name) != NULL)
{
printf("%s", address_book_content);
pos = ftell(show_address_book);
fseek(show_address_book, 27, pos); /// 27 in just a random number, I just want it to change the position of the cursor in the file
printf("%s", address_book_content);
}
}
return 0;
}
要实现预期的输出,以消除顶部和底部的填充。 Output i get This is the expected output
答案 0 :(得分:1)
我建议您使用一种稍微不同的方法,使用GraphicsPath类来测量和绘制Bitmap对象上的文本。
优点是GraphicsPath
类报告将绘制其引用的对象的实际坐标以及相对于特定Font的文本大小。
使用GraphicsPath.GetBounds()方法以 RectagleF
结构的形式返回这些度量。
基本构造函数假定Pen大小为1像素。
只有一个(小)细节需要处理:GDI +位图对象仅接受以整数值表示的尺寸,而所有其他度量都以浮点值表示。
我们需要补偿舍入,但通常仅为±1像素。
结果样本:
过程说明:
GraphicsPath
对象GraphicsPath
边界矩形Y
位置和“笔大小”所定义的坐标:我们需要< em>向后移动。 另请参阅以下有关GraphicsPath
和字体的注释:
Properly draw text using Graphics Path
示例代码:
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
string text = "This is my Text";
Font font = new Font("Arial", 52, FontStyle.Regular, GraphicsUnit.Point);
float penSize = 1f;
using (GraphicsPath path = new GraphicsPath())
{
path.AddString(text, font.FontFamily, (int)font.Style, font.Size, Point.Empty, StringFormat.GenericTypographic);
RectangleF textBounds = path.GetBounds();
using (Bitmap bitmap = new Bitmap((int)textBounds.Width, (int)textBounds.Height, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bitmap))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
g.Clear(Color.Black);
g.TranslateTransform(-penSize, -(textBounds.Y + penSize));
using (SolidBrush brush = new SolidBrush(Color.LightGreen))
{
g.FillPath(brush, path);
}
bitmap.Save("[Image Path]", ImageFormat.Png);
//Or: return (Bitmap)bitmap.Clone();
}
}