简体   繁体   English

如何使用Swift将SVG图像显示为UIImage

[英]How to display a SVG image as a UIImage with Swift

I need to change the icon of a GMSMarker (on Google Maps) to an SVG image (which I'm requesting from the web), any idea how to do this? 我需要将GMSMarker(在谷歌地图上)的图标更改为SVG图像(我正在从网上请求),任何想法如何做到这一点? Ive seen a few libraries which can do this but unsure how to use them! 我见过几个可以做到这一点但不确定如何使用它们的库! I basically need to convert an SVG image to a UIImage! 我基本上需要将SVG图像转换为UIImage!

I don't have enough reputation to comment so I had to put this in an answer, so sorry if it sounds more like a comment: 我没有足够的声誉来评论所以我不得不把它放在一个答案中,如果听起来更像是评论,那就很抱歉:

Anyway, You said you need to convert a SVG image to a UIImage. 无论如何,你说你需要将SVG图像转换为UIImage。 I've never done this, but I have created a UIImage from NSData before. 我从来没有这样做,但我之前已经从NSData创建了一个UIImage。 Perhaps there is a way to convert the SVG to NSData and then to UIImage (you might have to convert it from SVG to jpeg and then to NSData, I'm not sure. I would need to dig up the project where I did that.) 也许有一种方法可以将SVG转换为NSData然后转换为UIImage(您可能必须将其从SVG转换为jpeg然后转换为NSData,我不确定。我需要挖掘项目,我在那里做了。 )

Or maybe you could use the UIImage initializer called init?(contentsOfFile path: String). 或者你可以使用名为init的UIImage初始化器?(contentsOfFile path:String)。 This initializer takes one parameter, which is a String that represents the path to the image. 此初始化程序采用一个参数,该参数是表示图像路径的String。

Again, I've not tried any of this yet. 再说一次,我还没有尝试过这个。 Just trying to be of some help. 只是想要一些帮助。

Two potential methods. 两种可能的方法。

First, and easiest, is to export the SVG to PNG format. 首先,最简单的方法是将SVG导出为PNG格式。 Most apps will allow that modification - on Mac you can use Sketch, for example. 大多数应用程序都允许修改 - 例如,在Mac上你可以使用Sketch。 But it takes away the advantage of resolution-independent nature of SVG so it's not ideal. 但它消除了SVG独立于分辨率的优点,因此它并不理想。 You could export PNG for various resolutions and ship 1x/2x/3x with your app. 您可以导出各种分辨率的PNG,并使用您的应用程序发送1x / 2x / 3x。

The other option is to create a custom class derived from UIView , and override drawRect . 另一个选项是创建从UIView派生的自定义类,并覆盖drawRect In that, use functions to draw the SVG, which you can look at by opening the SVG (it's readable, like a text file, as you would know). 在那里,使用函数来绘制SVG,您可以通过打开SVG来查看它(它是可读的,就像您所知的文本文件一样)。 The drawRect would look something like this: drawRect看起来像这样:

let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPoint(x: 11.5, y: 17.5))
bezierPath.addLineToPoint(CGPoint(x: 28.5, y: 17.5))
// etc - you get the idea..
bezierPath.closePath()

Now, when you insert the custom UIView, it will automatically draw itself. 现在,当您插入自定义UIView时,它将自动绘制自己。 This is the approach used by PaintCodeApp (see www.paintcodeapp.com). 这是PaintCodeApp使用的方法(请参阅www.paintcodeapp.com)。 You could use the trial version of the app to generate the code, or buy the app. 您可以使用该应用的试用版来生成代码,或购买该应用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM