DDA直线扫描转换算法

作者:追风剑情 发布于:2019-3-24 11:02 分类:Algorithms

设待画线段两个端点坐标值是(x1, y1)和(x2, y2),不妨假定x1 < x2,待画线段所在直线方程是y=mx+b,则有

222.png

示例

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

        private void Initialize()
        {
            Bitmap bmp = new Bitmap(500, 500);
            this.pictureBox1.Image = bmp;
            //Graphics g = Graphics.FromImage(bmp);

            PointF p1 = new PointF() { X = 0, Y = 0 };
            PointF p2 = new PointF() { X = 100, Y = 200 };
            PointF p3 = new PointF() { X = 200, Y = 50 };
            DDALine(bmp, p1, p2, Color.Red);
            DDALine(bmp, p2, p3, Color.Yellow);
            DDALine(bmp, p1, p3, Color.White);
        }

        /// <summary>
        /// 绘制线段的数值微分分析器(Digital Differential Analyzer, DDA)
        /// </summary>
        /// <param name="bmp"></param>
        /// <param name="p1"></param>
        /// <param name="p2"></param>
        private void DDALine(Bitmap bmp, PointF p1, PointF p2, Color color)
        {
            double dx, dy, e, x, y;
            dx = p2.X - p1.X;
            dy = p2.Y - p1.Y;
            //这里必须取最大的那个距离差,不然会画成虚线(即,线条不连续)
            e = Math.Abs(dx) > Math.Abs(dy) ? Math.Abs(dx) : Math.Abs(dy);
            //为画线精确,应使画出的相邻点的坐标值最大相差1
            dx /= e;
            dy /= e;
            x = p1.X;
            y = p1.Y;

            for (int i = 0; i <= e; i++)
            {
                //(int)(x + 0.5)表示对x四舍五入
                //(int)(y + 0.5)表示对y四舍五入
                bmp.SetPixel((int)(x + 0.5), (int)(y + 0.5), color);
                x += dx;
                y += dy;
            }
        }
    }
}

运行测试
11111.png

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号