UIImagePNGRepresentation

UIImagePNGRepresentation

本文介绍了UIImagePNGRepresentation(UIImage())返回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.

谢谢.

推荐答案

UIImagePNGRepresentation() 将返回nil.从 UIKit文档:

初始化 UIImage UIImage()即可创建一个没有数据的UIImage.尽管图像不是nil,但它仍然没有数据.而且,由于图像没有数据,因此UIImagePNGRepresentation()仅返回nil.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 10:53