CALayer.compositingFilter适用于ObjectiveC但不适用于swift

时间:2016-06-26 01:32:04

标签: swift macos

下面的一些快速代码,它们都是干净的项目,ObjC代码可以工作,快速的代码不是吗?就我所见,但完全失败。图像显示但过滤器未在swift中应用,在objC中工作正常(OS X 10.11.3 Swift 2.2 Xcode 7.3)

import Foundation
import Cocoa

class MyView : NSView {
    let layer1 = CALayer()
    let layer2 = CALayer()
    let filter = CIFilter(name: "CILuminosityBlendMode")

    override func awakeFromNib() {

            wantsLayer = true

            layer!.addSublayer(layer1)

            if let imageRef = NSImage(named: "Back.jpg")
            {
                layer1.contents = imageRef
                layer1.anchorPoint = CGPointMake(0, 0)
                layer1.bounds = CGRectMake(0,0, imageRef.size.width, imageRef.size.height);
            }


            layer!.addSublayer(layer2)
            if let imageRef = NSImage(named: "Front.jpg")
            {
                layer2.contents = imageRef
                layer2.anchorPoint = CGPointMake(0, 0)
                layer2.bounds = CGRectMake(0,0, imageRef.size.width, imageRef.size.height);
            }

            layerUsesCoreImageFilters = true
            layer2.compositingFilter = [filter!]

    }

}

一些ObjC代码

MyView.h文件

@interface MyView : NSView {

    CALayer*    backLayer;
    CALayer*    frontLayer;

}

和MyView.m

#import <Foundation/Foundation.h>
#import "MyView.H"
#import <QuartzCore/QuartzCore.h>

@implementation MyView

- (void)awakeFromNib {

    [self setWantsLayer:YES];

    backLayer   = [CALayer layer];
    [self.layer addSublayer:backLayer];


    NSImage *nsimage = [NSImage imageNamed: @"Back.jpg"];
    backLayer.contents = nsimage;
    backLayer.anchorPoint = CGPointMake(0, 0);
    backLayer.bounds = CGRectMake(0,0, nsimage.size.width, nsimage.size.height);


    frontLayer  = [CALayer layer];
    [self.layer addSublayer:frontLayer];

    nsimage = [NSImage imageNamed: @"Front.jpg"];
    frontLayer.contents = nsimage;
    frontLayer.anchorPoint = CGPointMake(0, 0);
    frontLayer.bounds = CGRectMake(0,0, nsimage.size.width, nsimage.size.height);

    [self setLayerUsesCoreImageFilters:YES];

    CIFilter* filter = [CIFilter filterWithName:@"CILuminosityBlendMode"];
    frontLayer.compositingFilter = filter;
}
@end

1 个答案:

答案 0 :(得分:3)

在你的swift例子中,你传递的是一个数组。将最后一行更改为 layer2.compositingFilter = filter!