在iOS Swift中触摸时在UIImageView上绘制自定义形状

时间:2020-06-22 14:51:02

标签: swift cocoa-touch uiimageview cgcontext cgcontextdrawimage

我正在开发一个iOS Swift应用程序,该应用程序为用户提供了绘画的基本工具,例如钢笔,橡皮,油漆等。我想为其添加一个选项来绘制一些自定义形状,例如正方形,矩形,椭圆形,圆形,直线形等。

为此,我正在使用CGContextUIImageView进行操作。我正在使用touchesBegantouchesMovedtouchesEnded方法(UIKit方法)来处理相应的触摸事件。

要绘制UIImageView,我需要执行以下步骤:

let imgVw = UIImageView()
UIGraphicsBeginImageContext(self.view.bounds.size)
guard let context = UIGraphicsGetCurrentContext() else { return }
if let image = imgVw.image {
    image.draw(in: self.view.bounds)
}
context.move(to: fromPoint)
context.addQuadCurve(to: toPoint, control: fromPoint)  
context.setAlpha(1.0)
context.setLineCap(.round)
context.setLineWidth(5.0)
context.setStrokeColor(UIColor.red.cgColor)
context.setBlendMode(isEraser ? .clear : .normal)
context.strokePath()
let updatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
imgVw.image = updatedImage

toPointfromPoint正在从touches方法更新。

有什么方法可以绘制直线,椭圆形,圆形,正方形,矩形吗?

0 个答案:

没有答案