Search code examples
swiftuikitcore-graphicsdraw

how to draw images on top of circles in UIView swift


I'm trying to draw circles and in the middle of each circle, I want to draw an image. my circles work fine but I'm not getting along with the images.

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

The code below //draw PNGs is what my question is about but I posted the whole code.

thanks in advance for any help

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()
    }
} ```

Solution

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

    You can.

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

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