UIImage在UIImageView中的显示方式与保存到磁盘时的显示方式不同

时间:2015-08-01 22:39:21

标签: swift uiimageview uiimage image-rendering

我遇到问题,当我在操场内的UIImage检查时,我在游乐场中构建的UIImageView正确显示...

Here is the image as it appears in the playground.

...但是当我将其保存到磁盘时错误。

And here is the image as it appears when saved to disk.

以下是我用于构建/检查/保存UIImage的代码:

import UIKit
import XCPlayground

// Size of view and layers
let size = CGSize(width: 180, height: 180)

// Create a layer
let layer = CALayer()
layer.frame = CGRect(origin: CGPointZero, size: size)
layer.backgroundColor = UIColor.blackColor().CGColor

// And a sublayer
let sublayer = CALayer()
sublayer.frame = CGRect(origin: CGPointZero, size: size)
sublayer.cornerRadius = 180
sublayer.backgroundColor = UIColor.whiteColor().CGColor
layer.addSublayer(sublayer)

// Render the layer into an image
UIGraphicsBeginImageContext(size)
layer.renderInContext(UIGraphicsGetCurrentContext())
let im = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

// Inspect the image within the playground
let view = UIImageView(image: im)
XCPShowView("Container View", view: view)
view.layer.addSublayer(layer)

// Save the image to disk
let data = NSData(data: UIImagePNGRepresentation(im)!)
let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
var docs: String = paths[0] as String
let fullPath = docs.stringByAppendingPathComponent("icon.png")
let result = data.writeToFile(fullPath, atomically: true)

如何将图像渲染到磁盘以反映我在UIImageView中看到的内容?

1 个答案:

答案 0 :(得分:1)

如果半径大于制作圆圈,那么花瓣形的东西就是我期望看到的。如果单击"显示结果"在let view = UIImageView(image: im)行旁边的操场上的图标,它将以与存储在磁盘上相同的方式显示您的图像。见下文。我在试验它时改变了颜色,但是否则它就是你的代码......

所以我认为XCPShowView("Container View", view: view)中显示的内容不正确,而不是相反。

enter image description here