【问题标题】:How to set a fixed background image for CCButton如何为 CCButton 设置固定的背景图片
【发布时间】:2015-09-20 11:47:41
【问题描述】:

我正在尝试为 CCButton 设置背景图像,并确保它拉伸或最小化到 CCButton 的确切大小:

-(void)setBackgroundSpriteFrame: (NSString*)spriteFrameFileName
{
    NSString* fullFileName = [NSString stringWithFormat:@"%@.png", spriteFrameFileName];
    CCSpriteFrame *spriteFrame = [CCSpriteFrame frameWithImageNamed:fullFileName];
    [super setBackgroundSpriteFrame:spriteFrame forState:CCControlStateNormal];
    double scaleValue = self.contentSize.height / spriteFrame.rect.size.height;
    [self.background setScale:scaleValue];
    self.fileName = spriteFrameFileName;
}

此方法位于从 CCButton 继承的类中。

问题是我看到了背景图片,但它以一种奇怪的方式被挤压(见图片)并且没有最小化\拉伸到按钮的大小。

请注意,图片和按钮都是正方形,所以不需要单独缩放 X\Y,还要注意 CCButton 是使用 SprtieBuilder 生成的,而不是代码生成的。

'奇怪的样子':

原样:

谢谢

【问题讨论】:

  • 不能判断'奇怪'...你能显示实际的背景纹理吗?我假设上面的图片是渲染的 CCButton。

标签: objective-c cocos2d-iphone spritebuilder


【解决方案1】:

感谢“YvesLeBorg”的帮助,我设法解决了这个问题。

我正在发布对我有帮助的代码。 希望对其他人有所帮助。

NSString* fullFileName = [NSString stringWithFormat:@"%@.png", spriteFrameFileName];
CCTexture *texture = [CCTexture textureWithFile:fullFileName];
texture.contentScale = 2.0;
[super setBackgroundSpriteFrame:[texture createSpriteFrame] forState:CCControlStateNormal];
[self setScale:0.40];
self.fileName = spriteFrameFileName;

【讨论】:

    【解决方案2】:

    没有足够的声誉来评论,所以请原谅写一个答案。

    当我遇到同样的问题时,我在 cocos2d 论坛上找到了一个 net 解决方案(没有链接,sry)。总结一下 - 无需单独缩放图像。但应遵循 2 条规则:

    1) 图片应至少与元素 (CCButton) 大小相同,并且

    2) 不要忘记显式设置forState:CCControlStateNormal

    在这种情况下,不需要像您那样使用 contentScale

    【讨论】:

      猜你喜欢
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-29
      • 2023-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多