我正在将图形绘制到Winforms picturebox中。现在,我正在寻找可以“复制”一条线的可能性(点数),以便将两个结果线定位在与原始距离的固定距离之间。像这张照片一样,我有红线,想得到黑色的线:

线的图片http://img227.imageshack.us/img227/2341/linesb.png

我考虑过将线路上的几个像素上移动/右/向上右,但这会导致奇怪的重叠线。

还有其他方法可以做我想要的吗?任何想法都将不胜感激。谢谢!

有帮助吗?

解决方案

我创建了一个功能 确切地 几个月前,您需要作为图形布局算法的一部分。我在python和pyqt中写了这篇文章。我刚粘贴了代码 在Codepad. 。应该很容易地翻译成C#。

更新:

从我的python片段(喜欢做这些图形的东西:))中翻译成一对一。由于我的原始代码是为两个以上输出线设计的,因此我也将其带入了C#版本。对于两条黑线距离红色20像素,只需通过 width = 40num = 2. 。返回的锯齿阵列表示线数组(外部数组),每行用一个点(内部)表示。

public PointF[][] MultiplyLine(PointF[] line, int width, int num)
{
    if (num == 1) return new PointF[][] { line };
    if (num < 1) throw new ArgumentOutOfRangeException();
    if (line.Length < 2) return Enumerable.Range(0, num)
                  .Select(x => line).ToArray();

    Func<float, float, PointF> normVec = (x, y) => {
        float len = (float)Math.Sqrt((double)(x * x + y * y));
        return len == 0 ? new PointF(1f, 0f) : new PointF(x / len, y / len);
    };

    PointF[][] newLines = Enumerable.Range(0, num)
                  .Select(x => new PointF[line.Length]).ToArray();

    float numinv = 1f / (float)(num - 1), cor = 0f;
    PointF vec1 = PointF.Empty, vec2 = PointF.Empty, vec3 = PointF.Empty;

    int j = -1, i = -1;
    foreach (PointF p in line)
    {
        bool first = j == -1, last = j == line.Length - 2; j++;

        if (!last)
            vec1 = normVec(line[j + 1].Y - p.Y, -line[j + 1].X + p.X);
        if (!first)
            vec2 = normVec(-line[j - 1].Y + p.Y, line[j - 1].X - p.X);
        if (!first && !last)
        {
            vec3 = normVec(vec1.X + vec2.X, vec1.Y + vec2.Y);
            cor = (float)Math.Sin((Math.PI - 
                  Math.Acos(vec1.X * vec2.X + vec1.Y * vec2.Y)) / 2);
            cor = cor == 0 ? 1 : cor;
            vec3 = new PointF(vec3.X / cor, vec3.Y / cor);
        }

        i = -1;
        foreach (PointF[] newLine in newLines)
        {
            i++; cor = (float)width * ((float)i * numinv - 0.5f);
            vec1 = first ? vec1 : last ? vec2 : vec3;
            newLine[j] = new PointF(vec1.X * cor + p.X, vec1.Y * cor + p.Y);
        }
    }

    return newLines;
}

为了尝试一下,我取了这个小样本(与我的PYQT代码中的样本相同):

PointF[] pts = new PointF[] { 
    new PointF(100f, 100f), new PointF(300f, 200f), 
    new PointF(500f, 200f), new PointF(300f, 500f), 
    new PointF(600f, 450f), new PointF(650f, 180f), 
    new PointF(800f, 180f), new PointF(800f, 500f), 
    new PointF(200f, 700f)
};

pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
using(Graphics g = Graphics.FromImage(pictureBox1.Image)){
    g.DrawLines(new Pen(Color.Red), pts);

    foreach (PointF[] line in MultiplyLine(pts, 80, 14))
        g.DrawLines(new Pen(Color.Black), line);
}

这导致了此图形:

围绕线的大纲http://img41.imageshack.us/img41/8606/lines2.th.png

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top