如何通过编程将两个svg rect与C#连接起来?

时间:2019-06-27 14:43:50

标签: c# svg

您好,我是一名具有5个月经验的初级Web开发人员,我正在尝试构建锦标赛括号,我需要将它们与直线或路径连接起来,我的rects位于我用LINQ to XML生成的符号内。问题在于元素高度将要更改,并且线条必须跟随输入和输出点,在这些点上我放置了rect,但是我不知道它们的坐标,因为我不知道元素高度的改变。我将rects的初始Y坐标除以初始元素高度以获得百分比,但这并不是一个好的解决方案。

我已经尝试过使用jQuery .offset()方法,但是它起作用了,但是老板告诉我要使用C#。而且我们使用的是dotnet core 2.2,没有这种方法。

JavaScript

function connectElements(svg, path, startElem, endElem) {
    var svgContainer = $("#svgContainer");

    // if first element is lower than the second, swap!
    if (startElem.offset().top > endElem.offset().top) {
        var temp = startElem;
        startElem = endElem;
        endElem = temp;
    }

    // get (top, left) corner coordinates of the svg container   
    var svgTop = svgContainer.offset().top;
    var svgLeft = svgContainer.offset().left;

    // get (top, left) coordinates for the two elements
    var startCoord = startElem.offset();
    var endCoord = endElem.offset();

    // calculate path's start (x,y)  coords
    // we want the x coordinate to visually result in the element's mid point
    var startX = startCoord.left + 0.5 * startElem.outerWidth() - svgLeft;    // x = left offset + 0.5*width - svg's left offset
    var startY = startCoord.top + startElem.outerHeight() - svgTop;        // y = top offset + height - svg's top offset

    // calculate path's end (x,y) coords
    var endX = endCoord.left + 0.5 * endElem.outerWidth() - svgLeft;
    var endY = endCoord.top - svgTop;

    // call function for drawing the path
    drawPath(svg, path, startX, startY, endX, endY);

}

C#

public BracketLayout Layout(BracketGeneratorOptions opts){
float bracketOutput = 43f / 70f;
float bracketInput1 = 30f / 70f;
float bracketInput2 = 54f / 70f;

var l = new Line
       {
       StartX = p.X + opts.ElementWidth,
       StartY = p.Y + (int)(bracketOutput * opts.ElementHeight),
       EndX = p.X + opts.ElementWidth + (opts.RoundSpacing),                        
       EndY = i % 2 == 0 ? p.Y + (int)(roundOffset * (r + 1)) + (int)(bracketInput1 * opts.ElementHeight) : p.Y - spacing + (int)(roundOffset * (r + 1)) + (int)(bracketInput2 * opts.ElementHeight)
};
lines.Add(l);
}

public string Serialize(IEnumerable<BracketMatchViewModel> model, BracketLayout layout)
{
var svgDoc = XDocument.Parse(this.Template);
var defs = svgDoc.Root.Descendants().SingleOrDefault(x => x.Name.LocalName == "defs");

var bracketLines = layout.LinePath.Select(l => new XElement("line", new XAttribute("x1", l.StartX),
  new XAttribute("y1", l.StartY), new XAttribute("x2", l.EndX),
  new XAttribute("y2", l.EndY),
  new XAttribute("stroke", "white"), new XAttribute("stroke-width", "1px"))
  ).ToList();

defs.AddAfterSelf(bracketLines);
}

0 个答案:

没有答案