问题描述
如何将其转换为 Rectangle[]
数组?
解决方法
定义矩形
Rectangle(left,top,width,height)
Rectangle[] rectangles = new Rectangle[2]
{
new Rectangle(0,100,50),new Rectangle(200,200,};
List<Rectangle> rectangles = new List<Rectangle>();
Rectangle rect = new Rectangle();
rect.X = 5;
rect.Y = 10;
rect.Width = 100;
rect.Height = 50;
rectangles.Add(rect);
通过底部和右侧获取高度和宽度
int left = 100;
int top = 50;
int right = 400;
int bottom = 250;
int width = right - left;
int heigth = bottom - top;
Rectangle rect = new Rectangle(left,heigth);
绘制矩形数组
private void DrawRectangle()
{
Rectangle[] rectangles = new Rectangle[]
{
new Rectangle(0,new Rectangle(300,160,60)
};
foreach(var rect in rectangles)
{
System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Blue);
System.Drawing.Graphics formGraphics;
formGraphics = this.CreateGraphics();
formGraphics.FillRectangle(myBrush,rect);
myBrush.Dispose();
formGraphics.Dispose();
}
}
,
因此您需要从矩形坐标对象列表中创建一个 Rectangle 对象数组。
public class LTRB
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
public override string ToString() =>
$"Left: {Left},Top: {Top},Right: {Right},Bottom: {Bottom}";
}
Rectangle.FromLTRB 方法正是您所需要的,它根据坐标返回一个新的 Rectangle。
var rects = ltrbList.Select(x => Rectangle.FromLTRB(x.Left,x.Top,x.Right,x.Bottom)).ToArray();
理想情况下,创建扩展方法以获取 Rectangle
表单 LTRB
对象,以及 IEnumerable<Rectangle>
中的 IEnumerable<LTRB>
:
public static class LtrbExtensions
{
public static Rectangle ToRectangle(this LTRB ltrb) =>
Rectangle.FromLTRB(ltrb.Left,ltrb.Top,ltrb.Right,ltrb.Bottom);
public static IEnumerable<Rectangle> ToRectangles(this IEnumerable<LTRB> ltrbList) =>
ltrbList.Select(x => Rectangle.FromLTRB(x.Left,x.Bottom));
}
ToRectangle
var ltrb = new LTRB { Left = 0,Top = 0,Right = 50,Bottom = 200 };
var rec = ltrb.ToRectangle();
ToRectangles
var ltrbList = new List<LTRB>()
{
new LTRB {Left = 0,Bottom = 20},new LTRB {Left = 20,Top = 30,Right = 100,Bottom = 50},};
// To get IEnumerable<Rectangle>
var rects = ltrbList.ToRectangles();
// To get Rectangle[]
var rects = ltrbList.ToRectangles().ToArray();
// To get List<Rectangle>
var rects = ltrbList.ToRectangles().ToList();