在PictureBox上显示文字(用label或textbox背景色会有问题吧)

    最近的一个项目要在一张图上显示一个句子,先用了个PictureBox,然后往上面拽了个textbox,没想到,将textbox的backcolor设置为transparent,根本没有任何效果,图上文字底色还是白的。网上有说还要再把textbox的parent属性设为picturebox,但我的项目是PDA上的,用compack framefork,不支持这个操作,会发生运行错。

    于是用了下面的方法,从Image中得到graphics对象,然后用它画string,感觉效果还可以,下面是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DrawTextOnPicture
{
    public partial class DrawTextOnPicture : Form
    {
        public DrawTextOnPicture()
        {
            InitializeComponent();
            bFlag = true;
            LoadBitmap();
        }

        private void LoadBitmap()
        {
            Rectangle drawRect = new Rectangle();

            drawRect.X = pbFile.Location.X - pbFile.Width / 4;
            drawRect.Y = pbFile.Location.Y + pbFile.Height / 4;
            drawRect.Width = labelHide.Width;
            drawRect.Height = labelHide.Height;

            Image fileImage = new Bitmap(@"Program Files/DrawTextOnPicture/file.jpg");
            Graphics g = Graphics.FromImage(fileImage);

            g.DrawString(labelHide.Text, labelHide.Font, new SolidBrush(labelHide.ForeColor), drawRect);
            pbFile.Image = fileImage;
        }

        private void btnChangeText_Click(object sender, EventArgs e)
        {
            if (bFlag)
            {
                labelHide.Text = "您好 我的主人";
                bFlag = !bFlag;
            }
            else
            {
                labelHide.Text = "Hello lcrystal";
                bFlag = !bFlag;
            }

            LoadBitmap();
        }
    }
}

效果就是按一下按钮,换个显示。变量如下:

private System.Windows.Forms.PictureBox pbFile;
private System.Windows.Forms.Button btnChangeText;
private System.Windows.Forms.Label labelHide;
private bool bFlag;

我会把程序放到我的空间里的,大家可以下载看看。

你可能感兴趣的:(在PictureBox上显示文字(用label或textbox背景色会有问题吧))