关于c#画线

open422000 2012-09-07 11:02:49

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;
using System.Drawing.Drawing2D;

namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private PointF current;
private PointF movepf;

public Form1()
{
InitializeComponent();
}


private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{

current = e.Location;

}

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
movepf = e.Location;
Invalidate();
}

protected override void OnPaint(PaintEventArgs e)
{

Bitmap mp = new Bitmap(pictureBox1.Width, pictureBox1.Height);

Pen pen = new Pen(Color.Blue);

SolidBrush drawBrush = new SolidBrush(Color.Black);
using (Graphics g = Graphics.FromImage(mp))
{

g.DrawImage(mp, pictureBox1.ClientRectangle.X, pictureBox1.ClientRectangle.Y);
g.DrawLine(pen, current, movepf);

PointF pt1 = new PointF();

pt1.X = (current.X + movepf.X) / 2;
pt1.Y = (current.Y + movepf.Y) / 2;


g.DrawString("12345", this.Font, drawBrush, pt1);

using (Graphics gg = this.CreateGraphics())
{
gg.DrawImage(mp, pictureBox1.ClientRectangle.X, pictureBox1.ClientRectangle.Y);

}
}
base.OnPaint(e);
}


}
}





[img=C:\Users\Administrator\Desktop\1.png]
[/img]


就是想知道 我这样画线, 就一个窗体一个picturebox ,我想在picturebox里面画线,可是线条老出在form上面 怎么办呢
...全文
175 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Jia_H 2012-09-07
  • 打赏
  • 举报
回复
问题出在你用的Graphics是Form的(this.CreateGraphics()),用PictureBox的就可以画到PictureBox中了。不过效果估计不是你想要的。

代码改成如下的样子就可以了:

using (Graphics gg = Graphics.FromHwnd(pictureBox1.Handle)) //this.CreateGraphics())


你在MouseMove的事件中调用Invalidate来让Form重画从而调用到OnPaint方法,这样鼠标在PicutureBox上移动时就不停的画,还能看到什么12345呀。
Conmajia 2012-09-07
  • 打赏
  • 举报
回复
protected override void OnPaint(PaintEventArgs e)

这句是Form的Paint事件,你不觉得理所当然是画在窗体上吗。

你应该自己写个方法
private void pictureBoxPaint(object sender, PaintEventArgs e)

然后关联给你的pictureBox1.Paint事件

8,833

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 组件/控件开发
社区管理员
  • 组件/控件开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧