OSX UIGraphicsBeginImageContext

时间:2015-03-30 14:12:13

标签: ios macos nsimage uigraphicscontext uiimagepngrepresentation

我有一个iOS应用程序,我现在正在为Mac OSX创建。我有下面的代码将图像转换为1024的大小,并根据图像的宽高比计算出宽度。这适用于iOS,但显然不适用于OSX。我不知道如何创建NSImage的PNG表示或我应该使用的代替UIGraphicsBeginImageContext。有什么建议? 感谢。

        var image = myImageView.image

        let imageData = UIImagePNGRepresentation(image)
        let imageWidth = image?.size.width
        let calculationNumber:CGFloat = imageWidth! / 1024.0

        let imageHeight = image?.size.height
        let newImageHeight = imageHeight! / calculationNumber

        UIGraphicsBeginImageContext(CGSizeMake(1024.0, newImageHeight))
        image?.drawInRect(CGRectMake(0, 0, 1024.0, newImageHeight))
        var resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        let imageData = UIImagePNGRepresentation(resizedImage)

        let theImageData:NSData = UIImagePNGRepresentation(resizedImage)
        imageFile = PFFile(data: theImageData)

2 个答案:

答案 0 :(得分:2)

您可以使用:

let image = NSImage(size: newSize)
image.lockFocus()
//draw your stuff here
image.unlockFocus()
if let data = image?.TIFFRepresentation {
    let imageRep = NSBitmapImageRep(data: data)
    let imageData = imageRep?.representationUsingType(NSBitmapImageFileType.NSPNGFileType, properties: [:])
    //do something with your PNG data here
}

答案 1 :(得分:0)

我的两分钱 快速扩展以绘制带有部分重叠图像的图像:

extension NSImage {

    func mergeWith(anotherImage: NSImage) -> NSImage {

        self.lockFocus()
        //draw your stuff here

        self.draw(in: CGRect(origin: .zero, size: size))
        let frame2 = CGRect(x: 4, y: 4, width: size.width/3, height: size.height/3)
        anotherImage.draw(in: frame2)

        self.unlockFocus()
        return self
    }

}

最终效果:

enter image description here