在imageView上绘制具有清晰背景的矩形

时间:2017-11-28 09:28:37

标签: ios swift draw background-color cgrect

我正在尝试在imageView的顶部绘制一个带有随机边框颜色且背景清晰的矩形。我需要遍历一组坐标并为我的图像添加适当的矩形。我无法设法让矩形背景颜色变得清晰。代码如下:

// the draw class

class Draw: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func draw(_ rect: CGRect) {
        let h = rect.height
        let w = rect.width
        let color:UIColor = Palette.getRandomColour()

        //var drect = CGRect(x: (w * 0.25),y: (h * 0.25),width: (w * 0.5),height: (h * 0.5))
        let drect = CGRect(x: rect.minX ,y: rect.minY , width: w, height: h)
        let bpath:UIBezierPath = UIBezierPath(rect: drect)
        UIColor.clear.setFill()
        color.set()
        bpath.stroke()

        print("it ran")

        NSLog("drawRect has updated the view")                
    }  
}

// and in my viewDidLoad

for bp in sbp {
    if let master = Bodyparts.getID(bp.masterid) {
        let width  = master.x2 - master.x1
        let height = master.y2 - master.y1
        let k = Draw(frame: CGRect(origin: CGPoint(x: master.x1, y: master.y1), size: CGSize(width: width, height: height)))
        self.imgView.addSubview(k)
    }                        
}

1 个答案:

答案 0 :(得分:0)

您需要将背景设置为clear。这是一个可以复制和粘贴的游乐场:

import PlaygroundSupport
import UIKit

class Draw: UIView {

  override init(frame: CGRect) {
    super.init(frame: frame)
    backgroundColor = .clear
  }

  required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

  override func draw(_ rect: CGRect) {
    let h = rect.height
    let w = rect.width
    let color:UIColor = .red
    let drect = CGRect(x: rect.minX ,y: rect.minY , width: w, height: h)
    let bpath:UIBezierPath = UIBezierPath(rect: drect)
    UIColor.clear.setFill()
    color.set()
    bpath.stroke()
  }
}
let d = Draw(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .green
view.addSubview(d)
PlaygroundPage.current.liveView = view