daven11 daven11 - 3 months ago 58x
Swift Question

CALayer.compositingFilter works on ObjectiveC but not in swift

Some swift code below, they are both clean projects, the ObjC code works, the swift code doesn't? identical as far as I can see, but failing under swift. The images display but the filter isn't applied in the swift one, works fine in the 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


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);

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!]



Some ObjC code

the MyView.h file

@interface MyView : NSView {

CALayer* backLayer;
CALayer* frontLayer;


and the 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;


In your swift example, you are passing an array. Change the last line to layer2.compositingFilter = filter!.