2014年1月17日 星期五

使用Font類繪製文本(DrawString())

參考連結至:

http://blog.csdn.net/wwwiii520/article/details/2072010

利用Font的類別來定義文的的大小、樣式。

代碼如下:

public partial class Stringformat : Form
    {
        public Stringformat()
        {
            InitializeComponent();

            SetStyle(ControlStyles.Opaque, true);
            Point p = new Point(0, 0);
            Size s = new Size(500, 300);
            //Bounds = new Rectangle(0, 0, 500, 300);
            Bounds = new Rectangle(p, s);//窗體大小及相對於父客體的位置(0,0)
        }
        protected override void OnPaint(PaintEventArgs e)//重定義基類OnPaint()方法
        {
            Graphics g = e.Graphics;
            int y = 0;
            g.FillRectangle(Brushes.White, ClientRectangle);//繪制窗體背景色
            Rectangle rect = new Rectangle(0, y, 400, Font.Height);
            //g.FillRectangle(Brushes.Blue, rect);//墳兗一個矩形
            g.DrawRectangle(Pens.Blue, rect);//繪製一個矩形
            g.DrawString("This text is left justified.", Font, Brushes.Black, rect);
            y += Font.Height + 20;
            //Font.Dispose();//沒有創建對象,無須釋放資源

            Font afont = new Font("Arial", 16, FontStyle.Bold | FontStyle.Italic);
            rect = new Rectangle(0, y, 400, afont.Height);
            g.DrawRectangle(Pens.Blue, rect);
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Far;
            g.DrawString("This text is right justified.", afont, Brushes.Blue, rect,sf);
            y += afont.Height + 20;
            afont.Dispose();//創建了對象,須釋放資源

            afont = new Font("Courier Ncw", 12, FontStyle.Underline|FontStyle.Bold);
            rect = new Rectangle(0, y, 400, afont.Height);
            g.DrawRectangle(Pens.Blue, rect);
            sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;
            g.DrawString("This text is centered, and unederlined.", afont, Brushes.Blue, rect, sf);
            y += afont.Height + 20;
            afont.Dispose();

            afont = new Font("Times New Roman", 12);
            rect = new Rectangle(0, y, 400, afont.Height * 3);
            g.DrawRectangle(Pens.Blue, rect);
            string longString = "This text is much longer, and drawn ";
            longString += "into a rectangle that is higher than ";
            longString += "one line,so that it will wrap. It is ";
            longString += "very easy to wrap text using GDI+.";
            g.DrawString(longString, afont, Brushes.Black, rect);
            afont.Dispose();
        }
    }

沒有留言:

張貼留言