C#选项卡控件左边水平对齐图片

时间:2015-10-21 04:54:40

标签: c# image winforms add tabcontrol

我已按照msdn网站上的说明操作: https://msdn.microsoft.com/en-us/library/vstudio/ms404305%28v=vs.100%29.aspx 显示选项卡控件如下图所示:

enter image description here

这是代码:

private void tcMain_DrawItem(Object sender, DrawItemEventArgs e)
{
    Graphics g = e.Graphics;
    Brush _textBrush;

    TabPage _tabPage = tcMain.TabPages[e.Index];
    Rectangle _tabBounds = tcMain.GetTabRect(e.Index);

    if (e.State == DrawItemState.Selected)
    {
        _textBrush = new SolidBrush(Color.Red);
        g.FillRectangle(Brushes.Gray, e.Bounds);
    }
    else
    {
        _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
        e.DrawBackground();
    }

    Font _tabFont = new Font("Times New Roman", (float)22, FontStyle.Regular, GraphicsUnit.Pixel);

    StringFormat _stringFlags = new StringFormat();
    _stringFlags.Alignment = StringAlignment.Near;
    _stringFlags.LineAlignment = StringAlignment.Center;
    g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}

现在我想在标签控制按钮的左侧添加一张图片?我的意思是,如何在单词Book左侧显示图片?

从下面尝试了一些答案后,我最终得到了代码:

private void tcMain_DrawItem(Object sender, DrawItemEventArgs e)
    {
        Graphics g = e.Graphics;
        Brush _textBrush;

        TabPage _tabPage = tcMain.TabPages[e.Index];
        Rectangle _tabBounds = tcMain.GetTabRect(e.Index);

        if (e.State == DrawItemState.Selected)
        {
            _textBrush = new SolidBrush(Color.Red);
            g.FillRectangle(Brushes.Gray, e.Bounds);
        }
        else
        {
            _textBrush = new System.Drawing.SolidBrush(e.ForeColor);
            e.DrawBackground();
        }

        tcMain.ImageList = imgList;
        tcMain.TabPages[0].ImageIndex = 1;
        tcMain.TabPages[1].ImageIndex = 0;
        tcMain.TabPages[2].ImageIndex = 3;
        tcMain.TabPages[3].ImageIndex = 2;

        Rectangle tabImage = tcMain.GetTabRect(e.Index);
        tabImage.Size = new Size(40, 40);

        g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageIndex], tabImage);

        Font _tabFont = new Font("Times New Roman", (float)22, FontStyle.Regular, GraphicsUnit.Pixel);

        StringFormat _stringFlags = new StringFormat();
        _stringFlags.Alignment = StringAlignment.Center;
        _stringFlags.LineAlignment = StringAlignment.Center;
        g.DrawString(_tabPage.Text, _tabFont, _textBrush, _tabBounds, new StringFormat(_stringFlags));
    }

然后当我对结果拍摄快照时,它会像这样: enter image description here

enter image description here

一直刷新

1 个答案:

答案 0 :(得分:1)

您可以向项目添加ImageList控件并向其添加一些图片,并设置ImageIndex的{​​{1}}属性。然后在TabPages事件中使用DrawImage()方法。

DrawItem

您也可以使用Rectangle tabImage = tcMain.GetTabRect(e.Index); tabImage.Size = new Size(16, 16); g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageIndex], tabImage); 代替ImageKey

ImageIndex

如果您以编程方式添加g.DrawImage(tcMain.ImageList.Images[_tabPage.ImageKey], tabImage); ImageList,请执行以下操作:

ImageIndex