用笔进行抗锯齿

时间:2015-05-21 23:56:50

标签: c# graphics antialiasing

在我的代码中,我使用图形和笔来创建一个类似于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;
        }
    }
  }
}

1 个答案:

答案 0 :(得分:0)

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

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