我正在开发的 Sprite Kit 游戏使用自定义 slider 作为颜色选择器(颜色是从 slider 轨迹图形中选取的,它是一个包含渐变的 UIImage
)。
我研究过使用自定义的 UISlider
,但是标准的 IOS UI 控件不能很好地与 Sprite Kit 的场景一起播放:它们很难相对于场景的其余部分定位(因为它们存在作为主视图的 subview 而不是作为 SKScene
的一部分),它们突然出现(而不是与场景的其余部分一起过渡)并且必须在退出场景时手动删除。简而言之,实现它们很痛苦,而且它们不能无缝集成。
我已经开始使用 SKSpriteNode
实现自定义 slider ,构建于 Graf的 excellent SKButton class , 并将 slider 轨道和 handle 放置到位。 handle 沿着轨道左右滑动,并设置一个介于 0 和 1 之间的值(就像 UISlider
)。我将此类称为 SKSlider
。
我想做的是将 SKSlider
传递给 @selector
,就像传递 UISlider
一样,所以我可以在 SKScene
中为要执行的 slider 定义一个函数:
[mySlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
当 slider 发生变化时,我尝试调用的函数如下所示:
-(UIColor*)getRGBAFromImage:(UIImage*)image atX:(float)xp atY:(float)yp
{
NSMutableArray *resultColor = [NSMutableArray array];
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height,
bitsPerComponent, bytesPerRow, colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yp) + xp * bytesPerPixel;
CGFloat red = (rawData[byteIndex] * 1.0) /255.0;
CGFloat green = (rawData[byteIndex + 1] * 1.0)/255.0 ;
CGFloat blue = (rawData[byteIndex + 2] * 1.0)/255.0 ;
CGFloat alpha = (rawData[byteIndex + 3] * 1.0) /255.0;
byteIndex += 4;
UIColor *color = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
[resultColor addObject:color];
NSLog(@"width:%i hight:%i Color:%@",width,height,[color description]);
free(rawData);
return color;
}
(已找到代码 here,感兴趣的可以看看。)
但我不确定应该如何在 SKSlider
的界面中进行设置。有人能指出我正确的方向吗?
最佳答案
选择器的变量类型是SEL
。以下是您将如何声明属性以跟踪目标和操作。 (请注意,SEL
是指向结构的指针,而不是指向对象的指针,因此指定 strong
或 weak
会扰乱编译器。)
@property (nonatomic, strong) id target;
@property (nonatomic) SEL action;
这是更新目标和操作的示例方法
- (void)changeTarget:(id)target action:(SEL)action
{
self.target = target;
self.action = action;
}
这就是你如何调用目标上的 Action 方法
[self.target performSelector:self.action withObject:self afterDelay:0.0];
注意self是作为参数传递给方法的,所以target中的方法签名应该是
- (void)someAction:(id)sender
关于ios - 使用 Sprite Kit 创建自定义 slider - 如何传递 @selector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22220079/