【问题标题】:Antialiasing with Pen使用笔进行抗锯齿
【发布时间】:2015-05-22 08:01:03
【问题描述】:

在我的代码中,我使用图形和笔来创建一个类似于 Paint 的程序。由于我已经实现了一个允许用户更改画笔宽度的轨迹栏,因此我想让线条更平滑。我知道必须使用 SmoothingMode 和 AntiAlias,但我不知道如何实现它以及在哪里实现。 (我省略了更改笔的颜色、更改面板背景和擦除绘图等部分代码)

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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    bool mousePress;
    int xLast;
    int yLast;
    Graphics myGraphics;
    Pen myPen;

    private void Form1_Load(object sender, EventArgs e)
    {
        myGraphics = pnlBlackboard.CreateGraphics(); 
        myPen = new Pen(Color.Gray, 1);
        mousePress = false;
    }
    private void pnlBlackboard_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            mousePress = true;
            xLast = e.X;
            yLast = e.Y;
        }
    }

    private void pnlBlackboard_MouseMove(object sender, MouseEventArgs e)
    {
        if (mousePress)
        {
            myGraphics.DrawLine(myPen, xLast, yLast, e.X, e.Y);
            xLast = e.X;
            yLast = e.Y;
        }
    }

    private void pnlBlackboard_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            myGraphics.DrawLine(myPen, xLast, yLast, e.X, e.Y);
            mousePress = false;
        }
    }
    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        myGraphics.Dispose();
        myPen.Dispose();
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        this.Close(); 
    }

    private void trackBar1_Scroll(object sender, EventArgs e)
    {
        if (trackBar1.Value == 0)
        {
            myPen.Width = 1;
        }
        else if (trackBar1.Value == 1)
        {
            myPen.Width = 4;
        }
        else if (trackBar1.Value == 2)
        {
            myPen.Width = 6;
        }
        else if (trackBar1.Value == 3)
        {
            myPen.Width = 8;
        }
        else if (trackBar1.Value == 4)
        {
            myPen.Width = 12;
        }
        else if (trackBar1.Value == 5)
        {
            myPen.Width = 20;
        }
    }
  }
}

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 呃,CreateGraphics 不好。最小化您的表单将删除所有内容。使用位图中的绘制事件或图形对象。

标签: c# graphics antialiasing


【解决方案1】:

可以在 DrawLine 等之前使用。例如:

myGraphics.SmoothingMode = SmoothingMode.AntiAlias;
myGraphics.DrawLine(myPen, 0, 0, 12, 8);

【讨论】:

  • 当我尝试在 if 语句之前或之后插入代码行时,出现错误“当前上下文中不存在名称 'SmoothingMode'”。
  • @Emma 您需要对 System.Drawing.Drawing2D 命名空间的引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 2012-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-28
  • 2011-07-05
相关资源
最近更新 更多