zoukankan      html  css  js  c++  java
  • 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();//初始化,清空之前的绘图
            }
  • 相关阅读:
    算法:拓扑排序
    【欧拉计划2】Even Fibonacci numbers
    机房收费系统之模版方法使用
    VC运行时库
    数据库学习(6)——基本查询操作
    Attribute与Property的区别
    记C++类成员访问权限符二三事
    大年初五去颐和园
    2013年第6周六农历除夕下午
    大年初四晚上睡前
  • 原文地址:https://www.cnblogs.com/nb08611033/p/9035216.html
Copyright © 2011-2022 走看看