• C# winForm GDI+ 在矩形内绘制居中文本并时文本根据矩形大小进行缩放(转载自:http://www.it1352.com/20879.html)


    using System.Drawing;

    获取缩放后字体大小,函数:

            private Font FindFont(Graphics g, string longString, Size Rec, Font PreferedFont)//画布,文本,矩形,字体
            {//获得缩放后字体
                SizeF RealSize = g.MeasureString(longString, PreferedFont);//文本大小
                float HeightScaleRatio = Rec.Height / RealSize.Height;//高度缩放比例
                float WidthScaleRatio = Rec.Width / RealSize.Width;//宽度缩放比例
                float ScaleRatio = (HeightScaleRatio < WidthScaleRatio) ? ScaleRatio = HeightScaleRatio : ScaleRatio = WidthScaleRatio;//按高度缩放||按宽度缩放
                float ScaleFontSize = PreferedFont.Size * ScaleRatio;//缩放后的字体大小
                return new Font(PreferedFont.FontFamily, ScaleFontSize);
            }

    调用(在pictureBox的Paint事件中):

            private void PictureBox1_Paint(object sender, PaintEventArgs e)
            {
                Graphics g = e.Graphics;//画布
                Pen pen = new Pen(Color.Black) { Width = 0.2F };//画笔
                Font font = new Font("微软雅黑", 12);//字体
                Brush brush = new SolidBrush(Color.Black);//笔刷
                StringFormat strFormat = new StringFormat();//文本格式
                strFormat.LineAlignment = StringAlignment.Center;//垂直居中
                strFormat.Alignment = StringAlignment.Center;//水平居中
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;//抗锯齿
    
                Rectangle recHead = new Rectangle(10, 10, PictureBox1.Width-20, PictureBox1.Height-20);//矩形
                g.DrawRectangle(pen, recHead);//绘制矩形
                //文字内容
                Font goodFont = FindFont(g, info[0], recHead.Size, font);//缩放后字体
                g.DrawString("这是一段很长的文本", goodFont, brush, recHead, strFormat);//绘制文本(文本,字体,笔刷,矩形,文本格式)
            }
            private void PictureBox1_Resize(object sender, EventArgs e)
            {
                PictureBox1.Refresh();//初始化,清空之前的绘图
            }
  • 相关阅读:
    Sort it
    set 集合容器
    convertToString与ToString的区别
    string基本字符系列容器
    辗转相除法
    进程的总结
    进程池进阶
    进程池
    生产者消费者模型
    IPC :进程之间的通信
  • 原文地址:https://www.cnblogs.com/nb08611033/p/9035216.html
Copyright © 2020-2023  润新知