Cocos2D 2.0 - 改变CCSprite的矩形/拉伸精灵

时间:2012-06-19 19:40:43

标签: cocos2d-iphone

我创建了一个包含我将在课堂上使用的所有图像的地图集。如果这是一个从图像创建的精灵,我会创建它像

mySprite = [CCSprite spriteWithFile:@"white.png" rect:frame];

“white.png”是一个1x1像素的图像,我将其展开以覆盖整个CCSprite大小,该大小由该API上的rect:frame定义。

但是为了优化I / O和内存,我将white.png放在地图集中,我的想法是使用

创建它
mySprite = [CCSprite spriteWithSpriteFrameName:@"white.png"];

但这将创建1x1像素精灵。所以,我的想法是创建一个类别来扩展CCSprite这些行

@implementation CCSprite (CCSprite_Resize)


-(void)resizeTo:(CGSize) theSize
{
    CGFloat newWidth = theSize.width;
    CGFloat newHeight = theSize.height;


    float startWidth = self.contentSize.width;
    float startHeight = self.contentSize.height;

    float newScaleX = newWidth/startWidth;
    float newScaleY = newHeight/startHeight;

    self.scaleX = newScaleX;
    self.scaleY = newScaleY;

}

所以我可以这样做

mySprite = [CCSprite spriteWithSpriteFrameName:@"white.png"];
[mySprite resizeTo:frame.size];

并且将拉伸1x1精灵以覆盖我想要的尺寸。

问题是这不起作用。

任何线索?感谢。

2 个答案:

答案 0 :(得分:2)

支持你不要压倒像- (CGAffineTransform)nodeToParentTransform这样的事情。我正在使用带有cocos2d的Box2d物理,并提供模板类PhysicsSprite(CCSprite的子类)覆盖它,并且有一个错误:scale属性没有改变任何东西。我这样修好了:

- (CGAffineTransform)nodeToParentTransform
{
    b2Vec2 pos = body_->GetPosition();

    float x = pos.x * PTM_RATIO;
    float y = pos.y * PTM_RATIO;

    // Make matrix
    float radians = body_->GetAngle();
    float c = cosf(radians);
    float s = sinf(radians);

    if (!CGPointEqualToPoint(anchorPointInPoints_, CGPointZero))
    {
        x += c * -anchorPointInPoints_.x * scaleX_ + -s * -anchorPointInPoints_.y * scaleY_;
        y += s * -anchorPointInPoints_.x * scaleX_ + c * -anchorPointInPoints_.y * scaleY_;
    }

    // Rot, Translate Matrix
    transform_ = CGAffineTransformMake( c * scaleX_, s * scaleX_,
    -s * scaleY_, c * scaleY_,
    x, y );

    return transform_;
}

原文中,没有scaleX_scaleY_相乘。

答案 1 :(得分:0)

在您的情况下,您似乎可以使用CCLayerColor创建单色图层。没有必要使用精灵。

关于您的问题 - 确保frame.size不为零(CGSizeZero)