在二维数组中绘制椭圆

问题描述 投票:0回答:1

我正在尝试将椭圆绘制为二维数组。我将 x 和 y 作为左上角开始位置,将右下角 x 和 y 作为结束位置。

我正在尝试绘制一个恰好适合该矩形空间的椭圆。 当开始和结束坐标均匀时,我使用的算法有效,但当宽度坐标不均匀时,它的一个像素太短并且高度相同。

这是我的代码:

private void DrawEllipse(in NexusCoord start, in NexusCoord end, in NexusChar character)
{
    ThrowIfOutOfBounds(start);
    ThrowIfOutOfBounds(end);
    GetOrThrowColorIndex(character.Foreground, character.Background, nameof(character), out var foregroundColorIndex, out var backgroundColorIndex);

    var glyph = new Glyph(character.Value, foregroundColorIndex, backgroundColorIndex);

    var width = end.X - start.X;
    var height = end.Y - start.Y;

    var centerX = width / 2;
    var centerY = height / 2;

    var radiusX = start.X + centerX;
    var radiusY = start.Y + centerY;

    var x = 0;
    var y = centerY;

    var d1 = centerY * centerY - centerX * centerX * centerY;
    var dx = 2 * centerY * centerY * x;
    var dy = 2 * centerX * centerX * y;

    while (dx < dy)
    {
        SetGlyph(new NexusCoord(x + radiusX, y + radiusY), glyph);
        SetGlyph(new NexusCoord(-x + radiusX, y + radiusY), glyph);
        SetGlyph(new NexusCoord(x + radiusX, -y + radiusY), glyph);
        SetGlyph(new NexusCoord(-x + radiusX, -y + radiusY), glyph);

        if (d1 < 0)
        {
            x++;
            dx += 2 * centerY * centerY;
            d1 = d1 + dx + centerY * centerY;
        }
        else
        {
            x++;
            y--;
            dx += 2 * centerY * centerY;
            dy -= 2 * centerX * centerX;
            d1 = d1 + dx - dy + centerY * centerY;
        }
    }

    var d2 = centerY * centerY * ((x + 0.5) * (x + 0.5)) + centerX * centerX * ((y - 1) * (y - 1)) - centerX * centerX * centerY * centerY;

    while (y >= 0)
    {
        SetGlyph(new NexusCoord(x + radiusX, y + radiusY), glyph);
        SetGlyph(new NexusCoord(-x + radiusX, y + radiusY), glyph);
        SetGlyph(new NexusCoord(x + radiusX, -y + radiusY), glyph);
        SetGlyph(new NexusCoord(-x + radiusX, -y + radiusY), glyph);

        if (d2 > 0)
        {
            y--;
            dy -= 2 * centerX * centerX;
            d2 = d2 + centerX * centerX - dy;
        }
        else
        {
            y--;
            x++;
            dx += 2 * centerY * centerY;
            dy -= 2 * centerX * centerX;
            d2 = d2 + dx - dy + centerX * centerX;
        }
    }
}

当我调用该代码在控制台中绘制它时

Graphic.DrawShape(NexusShape.Ellipse, new NexusCoord(10, 10), new NexusCoord(45, 35)));
它看起来像这样:

Console Screenshot

粉色矩形是需要填充的空间。

我尝试使用双精度和舍入,但这也不起作用。

c# algorithm 2d ellipse drawellipse
1个回答
0
投票

好吧,我不是 C# 专家,但如果

var type
是隐式类型定义,那么你应该小心它。当您在以下部分评估中心坐标时:

var centerX = width / 2;
var centerY = height / 2;

你最终得到的是整数。所以,在你的例子中:

centerX = 17
centerY = 12

而不是:

centerX = 17.5
centerY = 12.5

因此,要么在整个代码中仔细而明确地定义变量类型,要么可以这样修改代码:

var centerX = width / 2.0;
var centerY = height / 2.0;

这将强制这些变量被视为双精度。您可能需要在代码中的不同位置实现此“技巧”。

© www.soinside.com 2019 - 2024. All rights reserved.