里面的填充矩形文本矩形、文本、里面

2023-09-02 02:10:31 作者:故我

我使用GDI +绘制的图形对象的字符串。

我要的字符串,以适应pre定义的矩形内(不违反任何行)

时有这样做的,除了在循环中使用TextRenderer.MeasureString(),直到理想的尺寸则返回呢?

是这样的:

  DrawScaledString(图形克,字符串MyString的,长方形矩形)
 

解决方案

您可以使用ScaleTransform

 字符串的TestString = @Lorem存有悲坐阿梅德,consectetur adipiscing ELIT。
Suspendisse等nisl adipiscing nisl adipiscing ultricies交流拉克丝。
Vivamus malesuada爱神在美国东部时间egestas山雀tincidunt自由人porttitor。
Pellentesque sollicitudin egestas augue,交流commodo猫ultricies坐阿梅特。

BMP位图=新位图(300,300);
使用(VAR图形= Graphics.FromImage(BMP))
{
    graphics.FillRectangle(Brushes.White,graphics.ClipBounds);
    VAR stringsize的= graphics.MeasureString(的TestString,this.Font);
    VAR规模= bmp.Width / stringSize.Width;
    如果(规模< 1)
    {
        graphics.ScaleTransform(秤,秤);
    }
    graphics.DrawString(的TestString,this.Font,Brushes.Black,新的PointF());
}
bmp.Save(lorem.png,System.Drawing.Imaging.ImageFormat.Png);
 
Axure原型如何根据使用场景来设置文本样式

但是,你可能会得到一些别名效果。

编辑:

但是,如果你想改变字体大小,而不是我想你可以更改比例的字体大小,在code以上,而不是使用的尺度变换。既尝试和比较结果的质量。

I'm using GDI+ to draw a string on a Graphics object.

I want the string to fit inside a pre-defined rectangle (without breaking any lines)

Is there's anyway of doing this besides using TextRenderer.MeasureString() in a loop until the desirable size is returned?

something like:

DrawScaledString(Graphics g, string myString, Rectangle rect)

解决方案

You can use the ScaleTransform

string testString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Suspendisse et nisl adipiscing nisl adipiscing ultricies in ac lacus.
Vivamus malesuada eros at est egestas varius tincidunt libero porttitor.
Pellentesque sollicitudin egestas augue, ac commodo felis ultricies sit amet.";

Bitmap bmp = new Bitmap(300, 300);
using (var graphics = Graphics.FromImage(bmp))
{
    graphics.FillRectangle(Brushes.White, graphics.ClipBounds);
    var stringSize = graphics.MeasureString(testString, this.Font);
    var scale = bmp.Width / stringSize.Width;
    if (scale < 1)
    {
        graphics.ScaleTransform(scale, scale);
    }
    graphics.DrawString(testString, this.Font, Brushes.Black, new PointF());
}
bmp.Save("lorem.png", System.Drawing.Imaging.ImageFormat.Png);

But you might get some alias effects.

Edit:

But if you want to change the font size instead I guess you can change the font size with scale in the code above instead of using the scale transform. Try both and compare the quality of the result.

 
精彩推荐
图片推荐