如何在Swift中绘制图像? [英] How do I draw on an image in Swift?

查看:111
本文介绍了如何在Swift中绘制图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够以编程方式绘制图像,并保存该图像供以后使用。比如说,在图像上的特定x和y坐标上画一条线,保存图像,并将其显示在一个简单的视图控制器上。我将如何在Swift中执行此操作? (最好是Swift 2,我还在开发中,并没有将我的mac更新到Sierra)


更新:可能与将UIImage转换为CGLayer,绘制它,然后然后更新将它转换回UIImage。

I need to be able to programmatically draw on an image, and save that image for later use. Say, draw a line on specific x and y coordinates on the image, save the image, and display it onto a simple view controller. How would I go about doing this in Swift? (Preferably Swift 2, I am still in development and haven't updated my mac to Sierra)

Update: Possibly something to do with converting a UIImage to a CGLayer, drawing on it, and then converting it back to a UIImage.

推荐答案

这很简单:


  1. 制作图像图形上下文。 (在iOS 10之前,您可以通过调用 UIGraphicsBeginImageContextWithOptions 来完成此操作。在iOS 10中,还有另一种方法,UIGraphicsImageRenderer,但如果您不想要,则不必使用它。)

  1. Make an image graphics context. (Before iOS 10, you would do this by calling UIGraphicsBeginImageContextWithOptions. In iOS 10 there's another way, UIGraphicsImageRenderer, but you don't have to use it if you don't want to.)

将图像绘制(即复制)到上下文中。 (出于这个目的,UIImage实际上有 draw ... 方法。)

Draw (i.e. copy) the image into the context. (UIImage actually has draw... methods for this very purpose.)

画出你的线路上下文。 (这里有CGContext函数。)

Draw your line into the context. (There are CGContext functions for this.)

从上下文中提取结果图像。 (例如,如果您使用 UIGraphicsBeginImageContextWithOptions ,则可以使用 UIGraphicsGetImageFromCurrentImageContext 。)然后关闭上下文。

Extract the resulting image from the context. (For example, if you used UIGraphicsBeginImageContextWithOptions, you would use UIGraphicsGetImageFromCurrentImageContext.) Then close the context.

这篇关于如何在Swift中绘制图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆