0

I'm having a problem where a UIImage that I build in a playground appears correctly when I inspect it in a UIImageView within the playground...

Here is the image as it appears in the playground.

...but incorrectly when I save it to disk.

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

Here is the code I'm using to build/inspect/save the 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)

How can I render the image to disk to reflect what I see in the UIImageView?

sudo make install
  • 5,629
  • 3
  • 36
  • 48

1 Answers1

1

The petal shaped thing is what I expect to see if the radius is larger than what makes a circle. If you click the "Show result" icon in playground next to the let view = UIImageView(image: im) line, it will show your image the exact same way as it is stored on disk. See below. I changed the colors while experimenting with it, but otherwise it is your code...

So I think that what is shown in XCPShowView("Container View", view: view) is incorrect, not the other way around.

enter image description here

MirekE
  • 11,515
  • 5
  • 35
  • 28
  • Yes--I chose this example to highlight that point. What I was looking for more was an explanation of *why* the corner radius causes this difference, and how to render the image to disk to look the same. I've updated the question to make that more clear. – sudo make install Aug 01 '15 at 23:03
  • Thanks for clarification. – MirekE Aug 01 '15 at 23:44
  • Huh! Interresting. So there is no way to render it to disk exactly as it shows up in `XPCShowView`? Is this a *bug* in `XPCShowView`? – sudo make install Aug 02 '15 at 06:11