如何在 UIView 中的圆圈上绘制图像 swift

how to draw images on top of circles in UIView swift

我正在尝试画圆圈,我想在每个圆圈的中间画一个图像。 我的圈子工作正常,但我不喜欢这些图片。

不明白为什么不能直接画一个UIImage

下面的代码 //draw PNG 是我的问题,但我发布了整个代码。

提前感谢您的帮助

import UIKit
import CoreGraphics

enum Shape2 {
    case circle
    case Rectangle
    case Line
}
class Canvas: UIView {
    let viewModel = ViewModel(set: set1)
    var currentShape: Shape2?
  
    override func draw(_ rect: CGRect) {
        guard let currentContext = UIGraphicsGetCurrentContext() else {
            print("Could not get Context")
            return
        }
        drawIcons (user: currentContext)
    }
    
    private func drawIcons(user context: CGContext){
        for i in 0...viewModel.iconsList.count-1 {
            let centerPoint = CGPoint(x: viewModel.icons_coord_x[i], y: viewModel.icons_coord_y[i])
            
            context.addArc(center: centerPoint, radius: CGFloat(viewModel.Diameters[i]), startAngle: CGFloat(0).degreesToRadians, endAngle: CGFloat(360).degreesToRadians, clockwise: true)
            
            context.setFillColor(UIColor.blue.cgColor)
            //context.setFillColor(viewModel.iconsbackground_colors[i].cgColor)
            
            context.fillPath()
            context.setLineWidth(4.0)
            
            //draw PNGs:
            let image = UIImage(named: "rocket")!
            let ciImage = image.ciImage
            let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)
            let context2 = CIContext(options: nil)
            let cgImage = context2.createCGImage(ciImage ?? <#default value#>, from: ciImage?.extent ?? <#default value#>)
            context.draw(CGImage() as! CGLayer, in: imageRect)

        }
    }
    
    func drawShape(selectedShape: Shape2){
        currentShape = selectedShape
        setNeedsDisplay()
    }
} ```

I don't understand why I can't just draw an UIImage directly.

可以。

https://developer.apple.com/documentation/uikit/uiimage/1624132-draw

https://developer.apple.com/documentation/uikit/uiimage/1624092-draw