UIImagePNGRepresentation(UIImage())返回nil [英] UIImagePNGRepresentation(UIImage()) returns nil
问题描述
为什么UIImagePNGRepresentation(UIImage())
返回nil
?
我试图在测试代码中创建UIImage()
只是为了断言它已正确传递.
I'm trying to create a UIImage()
in my test code just to assert that it was correctly passed around.
我对两个UIImage的比较方法使用了UIImagePNGRepresentation()
,但是由于某种原因,它返回了nil
.
My comparison method for two UIImage's uses the UIImagePNGRepresentation()
, but for some reason, it is returning nil
.
谢谢.
推荐答案
返回值
包含PNG数据的数据对象;如果生成数据有问题,则为nil. 如果图像没有数据或基础CGImageRef包含不受支持的位图格式的数据,则此函数可能返回nil.
Return Value
A data object containing the PNG data, or nil if there was a problem generating the data. This function may return nil if the image has no data or if the underlying CGImageRef contains data in an unsupported bitmap format.
When you initialize a UIImage
by simply using UIImage()
, it creates a UIImage
with no data. Although the image isn't nil, it still has no data. And, because the image has no data, UIImagePNGRepresentation()
just returns nil
.
要解决此问题,您必须对数据使用UIImage
.例如:
To fix this, you would have to use UIImage
with data. For example:
var imageName: String = "MyImageName.png"
var image = UIImage(named: imageName)
var rep = UIImagePNGRepresentation(image)
imageName
是图像的名称,包含在应用程序中.
Where imageName
is the name of your image, included in your application.
要使用UIImagePNGRepresentation(image)
,image
不得为nil
,并且还必须具有数据.
In order to use UIImagePNGRepresentation(image)
, image
must not be nil
, and it must also have data.
如果要检查它们是否有任何数据,可以使用:
If you want to check if they have any data, you could use:
if(image == nil || image == UIImage()){
//image is nil, or has no data
}
else{
//image has data
}
这篇关于UIImagePNGRepresentation(UIImage())返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!