转换CAShapeLayer以在NSImageView

时间:2015-09-21 19:11:38

标签: swift nsview cashapelayer nsimageview

我试图为Mac应用程序移植一些iOS代码。我的代码如下:

func innerRing() {
    let innerRing = CAShapeLayer()
    let circleRadius: CGFloat = 105.0
    innerRing.frame = InnerRingView.bounds

    func circleFrame() -> CGRect {
        var circleFrame = CGRect(x: 0, y: 0, width: 2*circleRadius, height: 2*circleRadius)
        circleFrame.origin.x = CGRectGetMidX(InnerRingView.bounds) - CGRectGetMidX(circleFrame)
        circleFrame.origin.y = CGRectGetMidY(InnerRingView.bounds) - CGRectGetMidY(circleFrame)
        return circleFrame
    }

    innerRing.path = UIBezierPath(ovalInRect: circleFrame()).CGPath
    innerRing.lineWidth = 3.0
    innerRing.strokeStart = 0.0
    innerRing.strokeEnd = 1.0
    innerRing.fillColor = UIColor.clearColor().CGColor
    innerRing.strokeColor = UIColor(red: 147.0/255.0, green: 184.0/255.0, blue: 255.0/255.0, alpha: 1.0).CGColor
    InnerRingView.layer.addSublayer(innerRing)
}

此代码非常有效,尤其适用于调整填充颜色,笔触颜色和笔触开始/结束。

在我的Mac应用中,我有效地尝试使用相同的代码,但将其应用于NSImageView(我希望它能够出现在表格的每一行上,我会调整某些参数(例如颜色)基于该行的详细信息。

是否有人可以协助指导将此简单圈添加到NSImageView

1 个答案:

答案 0 :(得分:3)

为什么要使用NSImageViewNSImageView用于显示图像(图标,图片等)。

改为自定义NSView。请记住,与UIKit的UIView不同,NSView默认情况下不会获得图层,因此您需要通过将wantsLayer设置为true来告诉它。

像这样:

class CircleView: NSView {

    lazy var innerRing: CAShapeLayer = {
        let innerRing = CAShapeLayer()
        let circleRadius: CGFloat = 105.0
        innerRing.frame = self.bounds

        var circleFrame = CGRect(x: 0, y: 0, width: circleRadius, height: circleRadius)
            circleFrame.origin.x = CGRectGetMidX(self.bounds) - CGRectGetMidX(circleFrame)
            circleFrame.origin.y = CGRectGetMidY(self.bounds) - CGRectGetMidY(circleFrame)

        innerRing.path = CGPathCreateWithEllipseInRect(circleFrame, nil)
        innerRing.lineWidth = 3.0
        innerRing.strokeStart = 0.0
        innerRing.strokeEnd = 1.0
        innerRing.fillColor = NSColor.clearColor().CGColor
        innerRing.strokeColor = NSColor(red: 147.0/255.0, green: 184.0/255.0, blue: 255.0/255.0, alpha: 1.0).CGColor
        return innerRing
    }()

    override func awakeFromNib() {
        super.awakeFromNib()

        wantsLayer = true
        layer = CALayer()
        layer?.addSublayer(innerRing)
    }

}