用钢笔抗锯齿

本文关键字: | 更新日期: 2023-09-27 17:50:24

在我的代码中,我使用图形和笔来创建一个类似于Paint的程序。因为我已经实现了一个允许用户改变笔的宽度的跟踪条,所以我想让线条更流畅。我知道平滑模式和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;
        }
    }
  }
}

用钢笔抗锯齿

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

myGraphics.SmoothingMode = SmoothingMode.AntiAlias;
myGraphics.DrawLine(myPen, 0, 0, 12, 8);
相关文章:
  • 没有找到相关文章