C#-graphic-中在PictureBox上使用橡皮筋画线
想法是在原有图层上加上一个透明图层,在那上面画线段。
来获取两点位置和线段长度。
在winform项目中添加一个PictureBox控件,然后添加鼠标在PictureBox上的事件。
目前遇到了两个问题,
1.透明图层的添加,BufferedGraphics bg对象使用bg.Graphics.Clear(Color.Transparent);时背景为黑色,
如何设置透明色?
在网上看了许多,是用图像缓存技术来实现的。具体代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 橡皮技术3{
public partial class Form2 : Form{
//存放直线对象的集合
List<Line> lines = new List<Line>();
//起始点
Point mStartPoint = Point.Empty;
public Form2(){
InitializeComponent();
}
//在图片对象上点击时
private void pictureBox1_MouseDown(object sender, MouseEventArgs e){
if (e.Button == MouseButtons.Left)
{
//点击左键,存入起始点
mStartPoint = e.Location;
}
}
//在图片上移动时,绘制直线
private void pictureBox1_MouseMove(object sender, MouseEventArgs e){
if (e.Button==MouseButtons.Left&& mStartPoint!=null){
drawlines(pictureBox1.CreateGraphics(), mStartPoint, e.Location);//按住左键不放绘制
}
}
//在松开左键时,存储点击,需要判定有无起始点,每次绘制结束后都要清空起始点
private void pictureBox1_MouseUp(object sender, MouseEventArgs e){
if (!mStartPoint.IsEmpty){
Line line = new Line(mStartPoint, e.Location);
lines.Add(line);
mStartPoint = Point.Empty;
}
}
private void drawlines(Graphics g, Point mPoint1, Point mPoint2){
BufferedGraphicsContext context = BufferedGraphicsManager.Current;//开辟空间
BufferedGraphics bg = context.Allocate(g,new Rectangle(0,0,PictureBox1.Width,PictureBox1.Height));//开辟空间的大小
bg.Graphics.Clear(Color.White);
//在缓冲区上画线
foreach (Line line in lines) {
line.Draw(bg.Graphics);
}
//在缓存图层中画直线的样式,并没有实际显示,尽量与绘图的样式一致
bg.Graphics.DrawLine(SystemPens.ControlText, mPoint1, mPoint2);
bg.Render();
bg.Dispose();
bg = null;
}
//通过paint绘制
private void pictureBox1_Paint(object sender, PaintEventArgs e){
foreach (Line line in lines){
line.Draw(pictureBox1.CreateGraphics());
}
}
}
}