Draw Image
We will draw an image at the point clicked. This loads two images, one from a specific file name, the other from the application path.
We alternate between two images that are transparent gifs.
Add this code, creating the MouseClick event using the lightening bolt in the form properties to select the mouse click event:
// Programmer: Janet Joy
// Illustrate loading image from specific file vs from application path.
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 DrawImage
{
public partial class Form1 : Form
{
// Load the images just once.
Image fish = Image.FromFile(@"c:/zebra0.com/csharp/images/fish.gif");
// Load an image from the application path. This is the where the exe file is: ../bin/debug directory.
Image bird = Image.FromFile(Application.StartupPath + @"\bird.png");
// Num % 2 is used to alternate the images.
int num = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
// Get the graphics of the form.
Graphics g = this.CreateGraphics();
// Draw the picture at point clicked.
if(num%2==0) g.DrawImage(bird, e.X, e.Y);
else g.DrawImage(fish, e.X, e.Y);
// Alternate between bird and fish.
num++;
}
}
}
To Do: Experiment! Try create an array of images and
select one randomly from the array.