【问题标题】:how to draw images on top of circles in UIView swift如何在 UIView swift 中的圆圈顶部绘制图像
【发布时间】:2020-12-12 02:27:43
【问题描述】:

我正在尝试绘制圆圈,并且在每个圆圈的中间,我想绘制一个图像。 我的圈子工作正常,但我与图片不合。

我不明白为什么我不能直接绘制 UIImage。

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

提前感谢您的帮助

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

【问题讨论】:

  • 这是因为image.ciImage 不存在。这不是基于 CIImage 的 UIImage。这是一个普通的 UIImage。要绘制 UIImage,只需在图像上直接调用draw!您可以消除四行无意义的代码。
  • 你在做一些完全没有必要的事情。您所要做的就是在 draw 方法中绘制一个图像,并设置它的位置。
  • 但我必须将其称为“context.draw(image: CGImage, in: CGRect)” 不是吗?因为 Xcode 只允许我在 draw 中放置一个 CGImage
  • 非常感谢,我现在知道了。我做的太复杂了?????????

标签: swift uikit core-graphics draw


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-08
  • 2015-10-20
  • 2021-10-15
  • 1970-01-01
相关资源
最近更新 更多