C#将图片框添加到面板

时间:2011-12-28 14:32:17

标签: c# winforms panel

我有一个名为panel3的面板,可在'Form1.cs'中找到。在这个小组中,我画了5行代表音乐人员。

现在我想将钢琴上的音符图片添加到音乐人员手中。基本上,我想在音乐人员的特定位置添加一个图片框。

为了做到这一点,我在'Staff.cs'中创建了一个名为'addPictureBox'的方法来构建一个图片框,并在每次按下一个键时将它放在面板上。

这是相关代码。问题是面板上没有显示图片框。在panel3中只能看到之前绘制的线条。

我该怎么办才能解决这个问题?为什么图片框没有显示在panel3中?感谢。

修改

感谢您的帮助:)我已经解决了问题

2 个答案:

答案 0 :(得分:3)

恕我直言,放置图片框并不是一个好主意 - 它不透明。所以我建议你手动绘制笔记。例如:


创建基本笔记类:

public class Note
{
    public Point Location { get; set; } 

    public virtual void Draw(Graphics g)
    {

    }
}

创建笔记,让我们说简单,困难和图片(绘制图片):

public class SimpleNote:Note
{
    public SimpleNote(Point position)
    {
        Location = position;
    }

    public override void Draw(Graphics g)
    {
        g.FillEllipse(Brushes.Red, Location.X, Location.Y, 5, 5);
        g.DrawLine(new Pen(Color.Red), Location.X+5, Location.Y, Location.X+5, Location.Y-15);
    }
}

public class DifficultNote:Note
{
    public DifficultNote(Point position)
    {
        Location = position;
    }

    public override void Draw(Graphics g)
    {
        SimpleNote left = new SimpleNote(Location);
        SimpleNote right = new SimpleNote(new Point(Location.X + 20, Location.Y));

        left.Draw(g);
        right.Draw(g);
        g.DrawLine(new Pen(Color.Red), Location.X+5, Location.Y - 15, Location.X+25, Location.Y-15);
    }
}

public class PictureNote:Note
{
    private Image _image;
    public PictureNote(Image image, Point position)
    {
        Location = new Point(position.X - image.Width/2, position.Y - image.Height/2);
        _image = image;
    }

    public override void Draw(Graphics g)
    {
        g.DrawImage(_image, Location);
    }
}

在Staff类中添加注释列表,并在OnPaint方法中调用draw方法:

public List<Note> noteList = new List<Note>(); 
protected override void OnPaint(PaintEventArgs e)
{
    int yPos = kOffset + staffIndex * kStaffSpacing;
    for (int bars = 0; bars < 5; bars++)
    {
        e.Graphics.DrawLine(Pens.Black, 0, yPos, kStaffInPixels, yPos);
        yPos += kBarSpacing;
    }

    foreach (var note in noteList)
    {
        note.Draw(e.Graphics);
    }
}

并在您的员工面板中创建鼠标单击事件处理程序,例如:

private void staff1_MouseClick(object sender, MouseEventArgs e)
{
    if(e.Button == MouseButtons.Left)
        staff1.noteList.Add(new SimpleNote(new Point(e.X, e.Y)));
    if(e.Button == MouseButtons.Right)
        staff1.noteList.Add(new DifficultNote(new Point(e.X, e.Y)));
    if(e.Button == MouseButtons.Middle)
            staff1.noteList.Add(new PictureNote(new Bitmap("c:\\note.png"), new Point(e.X, e.Y)));
       staff1.Invalidate();
}

结果(首先是图片,第二个难,第三个很简单):

enter image description here

P.S。代码不是最好的,我只是说明了我的想法。

答案 1 :(得分:0)

尝试致电:

pNewImage.BringToFront();

之后

panel3.Controls.Add(pNewImage);