zoukankan      html  css  js  c++  java
  • c#使用字符串的像素大小来绘制文本

    遇到的问题如下:

    代码:
    System.Drawing.Image imgBack = System.Drawing.Image.FromFile(sourceImg); //背景图片 System.Drawing.Image img = System.Drawing.Image.FromFile(destImg); //二维码图片 float fontSize = 12.0f;             //字体大小 Font font = new Font("宋体", fontSize);   //定义字体 int lineHeight = 30;//行高 float rectX = 300;//x坐标 float firstLineRectY = 800;//首行Y坐标 Graphics g = Graphics.FromImage(imgBack); g.DrawImage(img, 850, 850, 300, 300);             //float textWidth = textCompanyName.Length * fontSize; //文本的长度 float rectY = firstLineRectY;//300; float rectWidth = textCompanyName.Length * (fontSize + 8); float rectHeight = fontSize + 8; RectangleF textArea = new RectangleF(rectX, rectY, rectWidth, rectHeight);             Brush whiteBrush = new SolidBrush(Color.Black);//黑笔刷,画文字用 g.DrawString(textCompanyName, font, whiteBrush, textArea);

    使用Graphics绘制的文字如下,出现了错位,缺失的问题。

    问题的生产原因主要是由于背景图像是300DPI,代码中Font默认的分辨率为72像素,如果背景底图为72像素就不会有问题(如下使用72DPI背景图片绘制的是正常的)

    字体通常以点为单位,其中1点=1/72英寸。因此,10pt字体在每个屏幕分辨率上的大小(英寸)都是相同的,并且将根据屏幕分辨率和像素密度占用更多或更少的像素。以像素为单位测量的所有内容(如线条、形状等)都不会受到DPI的影响,但实际物理大小将根据屏幕分辨率和像素密度而变化。将代码更改为以像素为单位测量字体确实可以确保所有屏幕DPI设置中的文本都是相同的像素大小

     所以我们的代码使用以下方式来绘制文字:

    // Set up string.
    string measureString = "Measure String";
    Font stringFont = new Font("Arial", 16);
    
    // Measure string.
    SizeF stringSize = new SizeF();
    stringSize = e.Graphics.MeasureString(measureString, stringFont);//测量用指定的 Font 绘制的指定字符串
    
    // Draw rectangle representing size of string.
    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);
    
    // Draw string to screen.
    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));

    参考文章:

    https://www.cnblogs.com/goto/archive/2012/09/11/2680213.html

    https://stackoverflow.com/questions/10800264/windows-dpi-setting-affects-graphics-drawstring

  • 相关阅读:
    比较Maven和Ant
    解决浏览器缓存
    Servlet--HttpServletResponse的2个操作流的方法
    Servlet--j2e中文乱码解决
    java乱码详解(java中byte与char的转换)
    linux中操作java进程
    Servlet--超链接,表单提交,重定向,转发4种情况的路径
    物理路径,相对路径,绝对路径以及根目录
    Servlet--转发和重定向
    Servlet--传参和接参
  • 原文地址:https://www.cnblogs.com/gougou1981/p/13132040.html
Copyright © 2011-2022 走看看