问题描述
为什么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
.
谢谢.
推荐答案
UIImagePNGRepresentation()
将返回nil
.从 UIKit文档:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!