我不同意文档“很薄”。我从Core Image Programming Guide得到这一切
转换过滤器需要以下任务:
创建核心图像图像(CIImage 对象)以用于
过渡。
设置和安排计时器。
创建一个 CIContext 对象。
为滤镜创建一个 CIFilter 对象以应用于图像。
在 OS X 上,设置过滤器的默认值。
设置过滤器参数。
设置要处理的源图像和目标图像。
计算时间。
应用过滤器。
绘制结果。
重复步骤 8-10,直到转换完成。
获取图像并设置计时器
- (void)awakeFromNib {
NSTimer *timer;
NSURL *url;
thumbnailWidth = 340.0;
thumbnailHeight = 240.0;
url = [NSURL fileURLWithPath: [[NSBundle mainBundle]
pathForResource: @"boots" ofType: @"jpg"]];
[self setSourceImage: [CIImage imageWithContentsOfURL: url]];
url = [NSURL fileURLWithPath: [[NSBundle mainBundle]
pathForResource: @"skier" ofType: @"jpg"]];
[self setTargetImage: [CIImage imageWithContentsOfURL: url]];
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0/30.0
target: self
selector: @selector(timerFired:)
userInfo: nil
repeats: YES];
base = [NSDate timeIntervalSinceReferenceDate];
[[NSRunLoop currentRunLoop] addTimer: timer
forMode: NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer: timer
forMode: NSEventTrackingRunLoopMode];
}
设置过渡过滤器
- (void)setupTransition {
CGFloat w = thumbnailWidth;
CGFloat h = thumbnailHeight;
CIVector *extent = [CIVector vectorWithX: 0 Y: 0 Z: w W: h];
transition = [CIFilter filterWithName: @"CICopyMachineTransition"];
// Set defaults on OS X; not necessary on iOS.
[transition setDefaults];
[transition setValue: extent forKey: kCIInputExtentKey];
}
drawRect:复制机转场效果的方法
- (void)drawRect: (NSRect)rectangle {
CGRect cg = CGRectMake(NSMinX(rectangle), NSMinY(rectangle),
NSWidth(rectangle), NSHeight(rectangle));
CGFloat t = 0.4 * ([NSDate timeIntervalSinceReferenceDate] - base);
if (context == nil) {
context = [CIContext contextWithCGContext:
[[NSGraphicsContext currentContext] graphicsPort]
options: nil];
}
if (transition == nil) {
[self setupTransition];
}
[context drawImage: [self imageForTransition: t + 0.1]
inRect: cg
fromRect: cg];
}
应用过渡过滤器
- (CIImage *)imageForTransition: (float)t {
// Remove the if-else construct if you don't want the transition to loop
if (fmodf(t, 2.0) < 1.0f) {
[transition setValue: sourceImage forKey: kCIInputImageKey];
[transition setValue: targetImage forKey: kCIInputTargetImageKey];
} else {
[transition setValue: targetImage forKey: kCIInputImageKey];
[transition setValue: sourceImage forKey: kCIInputTargetImageKey];
}
[transition setValue: @( 0.5 * (1 - cos(fmodf(t, 1.0f) * M_PI)) )
forKey: kCIInputTimeKey];
CIFilter *crop = [CIFilter filterWithName: @"CICrop"
keysAndValues:
kCIInputImageKey, [transition valueForKey: kCIOutputImageKey],
@"inputRectangle", [CIVector vectorWithX: 0 Y: 0
Z: thumbnailWidth W: thumbnailHeight],
nil];
return [crop valueForKey: kCIOutputImageKey];
}
使用定时器更新显示
- (void)timerFired: (id)sender {
[self setNeedsDisplay: YES];
}
设置源图像和目标图像
- (void)setSourceImage: (CIImage *)source {
sourceImage = source;
}
- (void)setTargetImage: (CIImage *)target {
targetImage = target;
}
我还建议看下面的项目示例CITransitionSelectorSample