swift 如何使用核心图形实现自动布局

How to implement auto layout using core graphics in swift

我有个小问题。如您所见,我使用核心图形创建了一个三角形("context")和三角形的角度("retVinkel")。现在,当我 运行 Iphone 6s 上的应用程序时,它看起来很好,就在我想要它的中间并且大小合适。当然,三角形的宽度、高度和位置将是相同的,因为我已经在 UIView 中写下了坐标,例如 iPad air 它将位于右角而不是中间。

但是我该怎么做才能让三角形保持在中间并在屏幕尺寸扩大时扩大,以便在每个设备中填充相同数量的 space。我可以说 "move 20% pixels to the right and 30% pixels down" 这样三角形的面积会受到屏幕尺寸的影响吗?

    import UIKit

class TriangleDraw: UIView {


    override func drawRect(rect: CGRect) {
        let context = UIGraphicsGetCurrentContext()
        CGContextSetLineWidth(context, 2.0)
        CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor)
        CGContextMoveToPoint(context, 75, 400)
        CGContextAddLineToPoint(context, 325, 400)
        CGContextAddLineToPoint(context, 325, 225)
        CGContextAddLineToPoint(context, 75, 400)

        let retVinkel = UIGraphicsGetCurrentContext()
        CGContextSetLineWidth(retVinkel, 2.0)
        CGContextSetStrokeColorWithColor(retVinkel, UIColor.blackColor().CGColor)
        CGContextMoveToPoint(retVinkel, 300, 400)
        CGContextAddLineToPoint(retVinkel, 300, 375)
        CGContextAddLineToPoint(retVinkel, 325, 375)

        CGContextStrokePath(context)
        CGContextStrokePath(retVinkel)
    }

}

只需使用一定百分比的边界矩形而不是固定偏移量,例如

CGContextMoveToPoint(context, 0.15 * bounds.width, 0.80 * bounds.height)
CGContextAddLineToPoint(context, 0.45 * bounds.width, 0.80 * bounds.height)
...