我正在尝试向我的UIViewController
个实例中添加一个简单的粒子效果叠加层。我已经按照我发现的几个教程,但它们都没有处理视图控制器,它们的故事板只是一个没有控制器的视图,这让人感到困惑。
这是我的代码,我只想弄清楚为什么我看不到粒子效果。我错过了什么?视图本身肯定存在并添加(如果我改变它的颜色或我能看到的东西),它只是空的,并没有显示任何粒子效果。引用的图像文件肯定在项目和目标中,所以我在这里做错了什么呢?我是否需要以某种方式将CAEmitterLayer
添加到rainView
?这个教程没有提供任何帮助!
RainfallOverlay.h
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
@interface RainfallOverlay : UIView {
CAEmitterLayer *rainEmitter;
}
@end
RainfallOverlay.m
#import "RainfallOverlay.h"
@implementation RainfallOverlay
- (void) awakeFromNib
{
rainEmitter = (CAEmitterLayer *) self.layer;
rainEmitter.emitterPosition = CGPointMake(160, 100);
rainEmitter.emitterSize = CGSizeMake(10, 10);
rainEmitter.renderMode = kCAEmitterLayerAdditive;
CAEmitterCell *rain = [CAEmitterCell emitterCell];
rain.birthRate = 200;
rain.lifetime = 2.0;
rain.lifetimeRange = 1.5;
rain.color = [[UIColor colorWithRed: 0.2 green: 0.4 blue: 0.8 alpha: 0.1] CGColor];
rain.contents = (id) [[UIImage imageNamed: @"Particles_rain.png"] CGImage];
rain.name = @"rain";
rain.velocity = 150;
rain.velocityRange = 100;
rain.emissionRange = M_PI_2;
rain.emissionLongitude = 0.025 * 180 / M_PI;
rain.scaleSpeed = 0;
rain.spin = 0.5;
rainEmitter.emitterCells = [NSArray arrayWithObject: rain];
}
@end
ViewController.m viewDidLoad
RainfallOverlay *rainView = [[RainfallOverlay alloc] initWithFrame: CGRectMake(0, 0, 320, 250)];
[rainView setUserInteractionEnabled: NO];
[self.view bringSubviewToFront: rainView];
[self.view addSubview: rainView];
答案 0 :(得分:4)
有两个问题:
awakeFromNib
。在您的情况下,您必须实施initWithFrame
。layerClass
,self.layer
才会返回CAEmitterLayer
。只是将图层转换为CAEmitterLayer
不起作用。所以你的 RainfallOverlay 实现应该如下所示:
+ (Class)layerClass
{
return [CAEmitterLayer class];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
rainEmitter = (CAEmitterLayer *) self.layer;
// ... remaining setup
}
return self;
}