• 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();//初始化,清空之前的绘图
            }
  • 相关阅读:
    Web架构中的前端页面缓存
    Drools 使用Spring中的bean
    大型Java多用户商城系统设计开发的心得和困难
    正则表达式
    No ideal,no future
    关于sql 2005 assembly
    修改aspx输出的action地址 
    关于[META HTTPEQUIV="REFRESH" CONTENT=2]
    最简单的兼容firefox和ie的锚点方法
    【IIS】检索COM类工厂中CLSID为{0002450000000000C000000000000046}的组件时失败,错误: 80070005
  • 原文地址:https://www.cnblogs.com/nb08611033/p/9035216.html
Copyright © 2020-2023  润新知