给你
for i in 0..<60 {
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, rect.width / 2, rect.height / 2)
CGContextRotateCTM(ctx, CGFloat(Double(i) * M_PI / 30))
CGContextSetStrokeColorWithColor(ctx, UIColor.grayColor().CGColor)
CGContextTranslateCTM(ctx, 50, 0)
CGContextMoveToPoint(ctx, 0, 0)
if (i % 5 == 0) {
CGContextSetLineWidth(ctx, 3.0)
CGContextAddLineToPoint(ctx, -20, 0)
} else {
CGContextSetLineWidth(ctx, 2.0)
CGContextAddLineToPoint(ctx, -10, 0)
}
CGContextStrokePath(ctx)
CGContextRestoreGState(ctx)
}
导致
说明:
首先:校正的度数/弧度算术。
-
6 * i 以度为单位
- 需要以弧度表示 - 因此
* M_PI / 180
-
6 * i * M_PI / 180 可以简化为 i * M_PI / 30
其次:正确的几何形状。
- 在开始时按 x 和 y 平移,时钟在其矩形中居中
- 向右平移
50
- “向内”画一条线
20 或 10 长。向内含义negative
没有内部翻译的替代方案
for i in 0..<60 {
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, rect.width / 2, rect.height / 2)
CGContextRotateCTM(ctx, CGFloat(Double(i) * M_PI / 30))
CGContextSetStrokeColorWithColor(ctx, UIColor.grayColor().CGColor)
CGContextMoveToPoint(ctx, 50, 0)
if (i % 5 == 0) {
CGContextSetLineWidth(ctx, 3.0)
CGContextAddLineToPoint(ctx, 30, 0)
} else {
CGContextSetLineWidth(ctx, 2.0)
CGContextAddLineToPoint(ctx, 40, 0)
}
CGContextStrokePath(ctx)
CGContextRestoreGState(ctx)
}
完整的工作场所:
import UIKit
import XCPlayground
class CustomView : UIView {
override func drawRect(rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
for i in 0..<60 {
CGContextSaveGState(ctx)
CGContextTranslateCTM(ctx, rect.width / 2, rect.height / 2)
CGContextRotateCTM(ctx, CGFloat(Double(i) * M_PI / 30))
CGContextSetStrokeColorWithColor(ctx, UIColor.grayColor().CGColor)
CGContextTranslateCTM(ctx, 50, 0)
CGContextMoveToPoint(ctx, 0, 0)
if (i % 5 == 0) {
CGContextSetLineWidth(ctx, 3.0)
CGContextAddLineToPoint(ctx, -20, 0)
} else {
CGContextSetLineWidth(ctx, 2.0)
CGContextAddLineToPoint(ctx, -10, 0)
}
CGContextStrokePath(ctx)
CGContextRestoreGState(ctx)
}
}
}
let v = CustomView(frame: CGRectMake(0,0,200,200))
v.backgroundColor = .lightGrayColor()
XCPShowView("blabla", view: v)