我正在尝试了解有关MonoTouch的更多信息,因此我尝试使用Quartz2D绘图。我想创建一个示例,我以编程方式绘制n矩形。问题是只绘制了第一个。我认为第二个被第一个删除/清除/覆盖。
这是我的代码:
SingleViewMTViewController.cs
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
PointF locationOne = new PointF (5, 5);
PointF locationTwo = new PointF (5, 100);
SizeF size = new SizeF (120, 40);
DraggableRectangle tView = new DraggableRectangle (locationOne, size, UIColor.Yellow);
DraggableRectangle tView2 = new DraggableRectangle (locationTwo, size, UIColor.Brown);
DraggableRectangle[] views = new DraggableRectangle[2];
views [0] = tView;
views [1] = tView2;
View.AddSubviews (views);
}
DraggableRectangle.cs
public class DraggableRectangle : UIView
{
private CGPath path;
private PointF _targetLocation;
private SizeF _size;
private UIColor _fillColor = UIColor.Brown;
public DraggableRectangle (PointF targetLocation, SizeF size)
{
_targetLocation = targetLocation;
_size = size;
RectangleF frameRect = new RectangleF (_targetLocation.X, _targetLocation.Y, _size.Width, _size.Height);
this.Frame = frameRect;
this.BackgroundColor = UIColor.Clear; //without this, nothing is drawn
}
public DraggableRectangle (PointF targetLocation, SizeF size, UIColor fillColor):this(targetLocation,size)
{
_fillColor = fillColor;
}
public override void Draw (RectangleF rect)
{
//base.Draw (rect);
//works without base-call?
//get graphics context
using (CGContext gctx = UIGraphics.GetCurrentContext ()) {
//set up drawing attributes
_fillColor.SetFill ();
//create geometry
path = new CGPath ();
path.AddRect (new RectangleF (_targetLocation.X, _targetLocation.Y, _size.Width, _size.Height));
path.CloseSubpath ();
//add geometry to graphics context and draw it
gctx.AddPath (path);
gctx.DrawPath (CGPathDrawingMode.FillStroke);
}
}
使用MonoTouch绘制独立矩形有更好的方法吗?或者可以请某人解释一下,我做错了什么?
更新:多数民众赞成行。我能达到的最好的输出,但那只是不正确的"黄"和"布朗" http://www.bilder-upload.eu/show.php?file=81bfea-1329755225.png http://www.bilder-upload.eu/show.php?file=81bfea-1329755225.png
答案 0 :(得分:3)
实际上,两个矩形都是绘制的。问题是您的_targetLocation.Y
值。您要为视图的Frame
及其矩形设置相同的 Y 值,并使用Draw
方法绘制。
所以基本上,你的矩形是在视图边界之外绘制的。你的“棕色”视图的高度是40pt,而它的矩形是在Y = 100(在其可见部分下方)绘制的。
您必须区分这些值,因为视图的位置始终相对于其父坐标。
编辑:一个伪代码示例。
以下一行:
path.AddRect (new RectangleF (_targetLocation.X, _targetLocation.Y, _size.Width, _size.Height));
应该是这样的:
path.AddRect (new RectangleF ({Frame.Width >= something >= 0},
{Frame.Height >= something >= 0}, width, height);
编辑#2:
如果我更改路径的矩形,请使用以下命令:
path.AddRect (new RectangleF (0f, 0f, _size.Width, _size.Height));
这是我得到的......