How to change NSRect to CGRect?

后端 未结 3 953
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 03:23
-(void)drawRect : (NSRect)rect 
{    
        imgRect.orgin = NSZeroPoint;

        imgRect.size = [appleImage size];

        drawRect = [self bounds];

        [ap         


        
相关标签:
3条回答
  • 2021-01-19 03:49

    If you encounter this in iOS, such as with UIKeyboardFrameEndUserInfoKey, it's important to know that NSRect is a subclass of NSValue.

    if let rectValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let rect = rectValue.CGRectValue()
        // Use your CGRect
    }
    
    0 讨论(0)
  • 2021-01-19 03:58

    Just use these 2 Cocoa (no iOS) functions:

    CGRect NSRectToCGRect(NSRect nsrect);
    NSRect NSRectFromCGRect(CGRect cgrect);
    

    Have a look here to deepen the topic: http://cocoadev.com/CGRect

    0 讨论(0)
  • 2021-01-19 04:07

    Assuming you're using Apple's Foundation and not GNUStep or something else odd...


    Objective-C

    NSRect is just a typedef of CGRect (NSGeometry.h line 26-ish), so you can simply use either in place of the other anywhere.

    void takeCgRect(CGRect rect) {
        NSLog(@"A core graphics rectangle at %@ with size %@", NSStringFromCGPoint(rect.origin), NSStringFromCGSize(rect.size))
    }
    
    
    void takeNsRect(NSRect rect) {
        NSLog(@"A NeXTStep rectangle at %@ with size %@", NSStringFromPoint(rect.origin), NSStringFromSize(rect.size))
    }
    
    
    // ELSEWHERE:
    
    
    
    NSRect nsTest1 = NSMakeRect(1, 2, 3, 4)
    CGRect cgTest1 = CGRectMake(1, 2, 3, 4)
    CGRect cgTest2 = CGRectMake(100, 200, 300, 400)
    
    NSLog(@"%@", @(nsTest1 == cgTest1)) // 1
    
    
    takeCgRect(nsTest1) // A core graphics rectangle at {1.0, 2.0} with size {3.0, 4.0}
    takeNsRect(cgTest2) // A NeXTStep rectangle at {100.0, 200.0} with size {300.0, 400.0}
    

    Swift

    In Swift, NSRect is just a typealias of CGRect (NSGeometry.swift line 449-ish), so you can simply use either in place of the other anywhere.

    let nsTest1 = NSRect(x: 1, y: 2, width: 3, height: 4)
    let cgTest1 = CGRect(x: 1, y: 2, width: 3, height: 4)
    let cgTest2 = CGRect(x: 100, y: 200, width: 300, height: 400)
    
    print(nsTest1 == cgTest1) // true
    
    
    func takeCgRect(_ rect: CGRect) {
        print("A core graphics rectangle at \(rect.origin) with size \(rect.size)")
    }
    
    
    func takeNsRect(_ rect: NSRect) {
        print("A NeXTStep rectangle at \(rect.origin) with size \(rect.size)")
    }
    
    
    takeCgRect(nsTest1) // A core graphics rectangle at (1.0, 2.0) with size (3.0, 4.0)
    takeNsRect(cgTest2) // A NeXTStep rectangle at (100.0, 200.0) with size (300.0, 400.0)
    
    0 讨论(0)
提交回复
热议问题