UIBezierPath 的快速替代品,用于将大量正方形绘制到自定义视图

Fast alternatives to UIBezierPath for drawing a large number of squares to a custom view

我正在制作一个绘制基本元胞自动机的应用程序。目前我正在使用 UIBezierPath 在自定义 UIView 中绘制单元格:

 var path : UIBezierPath
    for (heightIndex, row) in stateMatrix!.enumerate() {
        for (widthIndex, cell) in row!.enumerate() {

            let myRect = CGRect(x: cellWidth * CGFloat(widthIndex), y: cellWidth * CGFloat(heightIndex), width: cellWidth, height: cellWidth)

            path = UIBezierPath(rect: myRect)
            if cell == "x" {
                Constants.OnColor.setFill()
                Constants.OnColor.setStroke()
            } else {
                Constants.OffColor.setFill()
                Constants.OffColor.setStroke()
            }
            path.fill()
            path.stroke()
        }
    }

我正在绘制的网格大约有 n * 6n 个单元格。当 n 很小时,这段代码工作正常,但它显然不能很好地扩展(在我的 iPhone 4s 上,n = 150,大约需要一分半钟)。显然,必须有比调用 UIBezierPath 几十万次更好的方法来做到这一点。解决这个问题的更好方法是什么?

为什么要使用 UIBezierPath?对于 150 * 150 的正方形,花费这样的时间来处理它是正常的 (https://en.wikipedia.org/wiki/Bézier_curve)。您可以使用 CoreGraphics 调用代替 UIBezierPath。这是 Obj-C 中的示例:

int side = 100; // number of squares in one side
int delta = 300 / side;

for (int i = 0; i < side; i++) {
    for (int j = 0; j < side; j++) {
        CGRect rectangle = CGRectMake(delta * i, delta * j, delta, delta);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.5);
        CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 0.5);
        CGContextFillRect(context, rectangle);
        CGContextStrokeRect(context, rectangle);
    }
}

这个例子用不到 0.1 秒来绘制这个数量的正方形。

2016-01-09 23:55:02.677
2016-01-09 23:55:02.741