iOS to Mac GraphicContext Explanation/Conversion

前端 未结 4 951
伪装坚强ぢ
伪装坚强ぢ 2020-12-30 05:57

I have been programming for two years on iOS and never on mac. I am working on a little utility for handling some simple image needs that I have in my iOS development. Anywa

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-30 06:30

    Here is a Swift (2.1 / 10.11 API-compliant) version of Cobbal's answer

        let size = NSMakeSize(50, 50);
        let im = NSImage.init(size: size)
    
        let rep = NSBitmapImageRep.init(bitmapDataPlanes: nil,
            pixelsWide: Int(size.width),
            pixelsHigh: Int(size.height),
            bitsPerSample: 8,
            samplesPerPixel: 4,
            hasAlpha: true,
            isPlanar: false,
            colorSpaceName: NSCalibratedRGBColorSpace,
            bytesPerRow: 0,
            bitsPerPixel: 0)
    
        im.addRepresentation(rep!)
        im.lockFocus()
    
        let rect = NSMakeRect(0, 0, size.width, size.height)
        let ctx = NSGraphicsContext.currentContext()?.CGContext
        CGContextClearRect(ctx, rect)
        CGContextSetFillColorWithColor(ctx, NSColor.blackColor().CGColor)
        CGContextFillRect(ctx, rect)
    
        im.unlockFocus()
    

提交回复
热议问题