macOS Swift CALayer.contents不会加载映像

时间:2018-07-12 20:53:50

标签: macos cocoa core-animation calayer nsimage

下面的代码创建一个红色矩形,该矩形经过动画处理以从左向右在视图中移动。我想从图像加载任意形状以叠加或替换矩形。但是,initializeCircleLayer函数中的circleLayer.contents = NSImage语句不会产生任何效果。诊断打印语句似乎可以验证图像是否存在并已找到,但是视图中没有图像。如何将图像放入图层中以替换动画的红色矩形?谢谢!

以下代码:

进口可可粉

ViewController类:NSViewController {

final class MySSLSocketFactory extends SSLSocketFactory {
    final SSLSocketFactory wrappedSSLSocketFactory;

    MySSLSocketFactory(SSLSocketFactory wrappedSSLSocketFactory) {
        this.wrappedSSLSocketFactory = wrappedSSLSocketFactory;
    }

    @Override
    public String[] getDefaultCipherSuites() {
        return getMyCipherSuites();
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return getMyCipherSuites();
    }

    @Override
    public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
        final SSLSocket sslSocket = (SSLSocket) wrappedSSLSocketFactory.createSocket(s, host, port, autoClose);

        // change the supported cipher suites on the socket, *before* it's returned to the client
        sslSocket.setEnabledCipherSuites(getMyCipherSuites());

        return sslSocket;
    }

    // other overloaded createSocket() methods do the same

    private String[] getMyCipherSuites() {
        // TODO: change this to return whatever cipher suites you want the server to use, from CipherSuite
        return new String[] {...};
    }
}

}

1 个答案:

答案 0 :(得分:0)

为什么不起作用

原因

circleLayer.contents = NSImage(named: NSImage.Name(rawValue:  "testImage"))?.cgImage

不起作用是因为它是对cgImage(forProposedRect:context:hints:)方法的引用,这意味着它的类型是

((UnsafeMutablePointer<NSRect>?, NSGraphicsContext?, [NSImageRep.HintKey : Any]?) -> CGImage?)? 

您可以通过将NSImage(named: NSImage.Name(rawValue: "testImage"))?.cgImage分配给局部变量并单击并单击以查看其类型来查看它。

编译器允许此分配,因为circleLayer.contentsAny?属性,因此实际上可以为其分配任何内容。

如何修复

从macOS 10.6开始,您可以将NSImage对象直接分配给图层contents

circleLayer.contents = NSImage(named: NSImage.Name(rawValue:  "testImage"))