【问题标题】:Trouble displaying an Image on my Panel无法在我的面板上显示图像
【发布时间】:2013-03-20 10:45:27
【问题描述】:

我正在尝试将游戏的图像绘制到 C# 面板上。我没有绘制任何图像,我无法弄清楚为什么从未调用过此方法:

private void playerPanel_Paint(object sender, PaintEventArgs e)

这是我的代码:

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

namespace FlightOfTheNavigator
{
    public partial class Form1 : Form
    {
        // Load Sprites
        public Bitmap playerShip = new Bitmap(FlightOfTheNavigator.Properties.Resources.testship);

        public Form1()
        {
            InitializeComponent();        
            SetupGame();
        }

        public void SetupGame()
        {
            // Setup Console
            txtConsole.Text = "Loading Ship Bios v3.4.12c ..." + 
                               Environment.NewLine + 
                               "Console Ready" + 
                               Environment.NewLine + 
                               "----------------------------------------------------------------------------------------" + 
                               Environment.NewLine +
                               Environment.NewLine;

            // Setup Basic Weapons
            listWeapons.Items.Add("Pulse Lazers");
            listWeapons.Items.Add("Cluster Missiles");

            // Set Shield Perecentage
            txtShields.Text = "0%";
        }

        private void trackShield_Scroll(object sender, EventArgs e)
        {
            txtShields.Text = "" + trackShield.Value + "%";
        }

        private void playerPanel_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = playerPanel.CreateGraphics();
            g.DrawImage(playerShip, 0, 0,100,100);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Invalidate the panel. This will lead to a call of 'playerPanel_Paint'
            playerPanel.Refresh();
        }
    }
}

【问题讨论】:

  • 确保面板的Paint事件附加到playerPanel_Paint
  • @Haden693:那是完全不同的问题。
  • 感谢独角兽解决了这个问题。自动生成的代码没有将面板链接到事件。这是解决方法; “this.playerPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.playerPanel_Paint);”。
  • 在较新的 C# 版本(8 岁或以下)中,您甚至可以编写 this.playerPanel.Paint += playerPanel_Paint;
  • 所以让我们来回答一下吧。

标签: c# image panel system.drawing


【解决方案1】:

确保面板的Paint 事件附加到playerPanel_Paint 方法。

打开 Desinger,选择面板 (playerPanel),按 F4 调出“属性”窗口,然后单击“属性”窗口上方的闪电以显示事件。检查那里的Paint 事件。如果为空,打开下拉菜单,选择playerPanel_Paint方法。

您也可以在代码中执行此操作。在InitializeComponent()之后将它放入表单的构造函数中:

this.playerPanel.Paint += PaintEventHandler(playerPanel_Paint);

【讨论】:

    猜你喜欢
    • 2011-05-24
    • 2015-05-17
    • 2020-10-04
    • 2013-10-31
    • 2013-03-24
    • 1970-01-01
    • 2016-06-28
    • 2020-08-20
    • 2012-05-15
    相关资源
    最近更新 更多