Where is CGRectGetMidX/Y in Swift 3

2019-04-19 03:01发布

IN Siwft 3, I could not find CGRectGetMidX and Y which I used to calclate position of nodes. Also I could not find CGPointMake. IN this case, how am I able to set nodes in the center of SKScene?

Thanks!

Update: I created a node and specified the position of it, by writing this way;

let node = SKSpriteNode()
node.position = CGPoint(x:self.frame.size.width/2, y:self.frame.size.height/2)
node.size = CGSize(width: 100, height: 100)
node.color = SKColor.red
self.addChild(node)

Why is it somewhere else like different place from the specified location? I firstly thought there was a change in Swift3 and the depresciation of CGPointMake caused this problem, but it does not seem like it is the cause. In this case, is the use of CGRect better? It is very helpful if you could write code that fixs this position issue. Again, thank you for your help.

标签: ios swift3
3条回答
Emotional °昔
2楼-- · 2019-04-19 03:18

In Swift you shouldn't use those old style notations. Just use the constructors and properties:

let point = CGPoint(x: 1, y: 2)
let rect = CGRect(x: 1, y: 2, width: 3, height: 4)
let mx = rect.midX
查看更多
男人必须洒脱
3楼-- · 2019-04-19 03:21

C global functions like CGRectGetMidX/Y, CGPointMake, etc. shouldn't be used in Swift (they're deprecated in Swift 2.2, removed in Swift 3).

Swift imports CGRect and CGPoint as native types, with initializers, instance methods, etc. They're much more natural to use, and they don't pollute the global name space as the C functions once did.

let point = CGPoint(x: 0, y: 0) //replacement of CGPointMake

let rect = CGRect(x: 0, y: 0, width: 5, height: 5) //replacement of CGRectMake

let midX = rect.midX //replacement of CGRectGetMidX
let midY = rect.midY //replacement of CGRectGetMidY

Their respect API reference is linked above. You might also find the CoreGraphics API reference handy too.

查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-04-19 03:33

Have too many center calculations in your code. Use this.

extension CGRect {
        var center : CGPoint  {
            get {
            return CGPoint(x:self.midX, y: self.midY)
            }
        }
    }
查看更多
登录 后发表回答