如何在SpriteKit中获取像素化纹理?

时间:2013-10-27 14:13:01

标签: ios sprite-kit

如何将SKTextureFilteringNearest设置为我所有SKTextures的默认过滤模式?如果我没有将过滤设置为最近,则表明我的所有精灵的边缘都是模糊的。

2 个答案:

答案 0 :(得分:2)

SpriteKit使用SKTextureFilteringLinear为所有纹理设置默认的filteringMode,从而产生模糊图像(特别是在缩放时)。要解决此问题,您可以为SKTextureSKTextureAtlas创建一个类别,并调用正确的方法。或者您可以使用方法调整textureWithImageNamed:

<强> SKTexture + DefaultSwizzle.h

#import <SpriteKit/SpriteKit.h>

@interface SKTexture (DefaultSwizzle)
@end

<强> SKTexture + DefaultSwizzle.m

#import "SKTexture+DefaultSwizzle.h"
#import <objc/runtime.h> // Include objc runtime for method swizzling methods

@implementation SKTexture (DefaultSwizzle)

+ (SKTexture *)swizzled_textureWithImageNamed:(NSString*)filename
{
    // This is the original. At this point the methods have already been switched
    // which means that `swizzled_texture*` is the original.
    SKTexture *texture = [SKTexture swizzled_textureWithImageNamed:filename];

    // Set 'nearest' as default mode
    texture.filteringMode = SKTextureFilteringNearest;

    return texture;
}

+ (void)load
{
    Method original, swizzled;

    original = class_getClassMethod(self, @selector(textureWithImageNamed:));
    swizzled = class_getClassMethod(self, @selector(swizzled_textureWithImageNamed:));
    // Swizzle methods
    method_exchangeImplementations(original, swizzled);
}

@end

答案 1 :(得分:0)

我提出了一个不同的解决方案,无需调整即可使原始方法完好无损:

@interface SKTexture (FilteringModeCategory)
+(SKTexture*) textureWithImageNamed:(NSString*)file
                      filteringMode:(SKTextureFilteringMode)mode;
+(SKTexture*) textureNearestFilteredWithImageNamed:(NSString*)file;
@end

实施:

@implementation SKTexture (FilteringModeCategory)

+(SKTexture*) textureWithImageNamed:(NSString*)file 
                      filteringMode:(SKTextureFilteringMode)mode
{
    SKTexture* tex = [SKTexture textureWithImageNamed:file];
    tex.filteringMode = mode;
    return tex;
}

+(SKTexture*) textureNearestFilteredWithImageNamed:(NSString*)file
{
    SKTexture* tex = [SKTexture textureWithImageNamed:file];
    tex.filteringMode = SKTextureFilteringNearest;
    return tex;
}

@end

随意重命名第二种方法。怎么样:crispyTextureWithImageNamed? :)

PS:SKTextureAtlas也可能需要相应的textureNamed:filteringMode:textureNearestFilteredNamed:类别方法。