![](/img/trans.png)
[英]Drawing a straight line in visual studio C# by the user along with the line moving along with the mouse?
[英]Drawing a straight line in C# windows form
我有一個簡單的Windows窗體程序,該程序允許用戶在圖片框中繪制直線。 有一條線,但是它超出了圖片框,在其中不可見(就像我所附的圖片一樣)。 我怎樣才能使行僅出現在圖片框中。 這是我的代碼:
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;
using System.Windows.Input;
namespace LinePOD
{
public partial class LineTest : Form
{
public LineTest()
{
InitializeComponent();
}
Point p1 = new Point();
Point p2 = new Point();
Pen pen = new Pen(Color.Magenta, 10);
private void LineTest_Load(object sender, EventArgs e)
{
}
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
p1 = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
p2 = e.Location;
Graphics g = this.CreateGraphics();
g.DrawLine(pen, p1, p2);
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.Aqua;
}
}
}
您可以創建一個與PictureBox大小相同的位圖,並在PictureBox的Paint事件中繪制該位圖。 然后在鼠標事件中繪制線條以繪制位圖。 這將在Windows中保留行以最小化/還原事件。 為了方便起見,我放置了整個代碼:
public partial class Form1 : Form
{
Bitmap bitmap;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
bitmap = new Bitmap(pictureBox1.ClientSize.Width,
pictureBox1.ClientSize.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
}
Point p1 = new Point();
Point p2 = new Point();
Pen pen = new Pen(Color.Magenta, 10);
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
p1 = e.Location;
}
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
p2 = e.Location;
Graphics g = Graphics.FromImage(bitmap);
g.DrawLine(pen, p1, p2);
pictureBox1.Invalidate();
g.Dispose();
}
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.BackColor = Color.Aqua;
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawImage(bitmap, 0, 0, bitmap.Width, bitmap.Height);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.