如何平铺Sprite Node的纹理?

时间:2015-02-06 01:08:10

标签: ios swift sprite-kit textures tiling

使用SpriteKit,我如何平铺一个水平重复的SKTexture来填充SKSpriteNode的宽度?这就是我到目前为止 - 只是拉伸纹理。

var header = SKSpriteNode()
let headerTexture = SKTexture(imageNamed: "inGameHeader-1.png")
header = SKSpriteNode(texture: headerTexture)
header.position = CGPoint(x: 0, y: CGRectGetMaxY(self.frame)-39)
header.size.width = CGRectGetWidth(self.frame)
header.size.height = 150
header.anchorPoint = CGPoint(x: 0,y: 1)
addChild(header)

4 个答案:

答案 0 :(得分:0)

可以在this answer找到基于使用SpriteKit着色器的工作实现。请注意,您需要导入标头以在Swift中使用它。

答案 1 :(得分:0)

这是我的解决方案:将图像发送到此函数,使用精灵的大小,然后是图块的大小。这将返回平铺的SKTexture。

-(SKTexture *)tiledTextureImage:(UIImage *)image ForSize:(CGSize)size tileSize:(CGSize)tileSize{

// First we create a new size based on the longest side of your rect
int targetDimension = (int)fmax(size.width,size.height);
CGSize targetSize = CGSizeMake(targetDimension, targetDimension);

// Create a CGImage from the input image and start a new image context.
struct CGImage *targetRef = image.CGImage;
UIGraphicsBeginImageContext(targetSize);
CGContextRef contextRef = UIGraphicsGetCurrentContext();

// Now we simply draw a tiled image
CGContextDrawTiledImage(contextRef, CGRectMake(0,0, tileSize.width,tileSize.height), targetRef);
UIImage *tiledTexture = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

// Finally create a texture and return it. 
return  [SKTexture textureWithImage:tiledTexture];
}

答案 2 :(得分:0)

你知道你可以通过resizableImageWithCapInsets在UIButton或UIImageView中执行此操作,因此,这是我的解决方案:

-(SKTexture *)textureWithImage:(UIImage *)image tiledForSize:(CGSize)size withCapInsets:(UIEdgeInsets)capInsets{
//get resizable image
image =  [image resizableImageWithCapInsets:capInsets];
//redraw image to target size
UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
[image drawInRect:CGRectMake(0, 0, size.width-1, size.height-1)];
[[UIColor clearColor] setFill];
//get target image
UIImage *ResultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// get texture
SKTexture * texture = [SKTexture textureWithImage:ResultImage];
return texture;
}

答案 3 :(得分:0)

这是Swift 3和4的静态函数。不使用扩展名,因为SKTexture类实际上没有指定的初始值设定项。

请注意,这不会非常高效。最好在使用前预加载纹理,或潜入自定义着色器的世界。

static func generateTiledTexture(size: CGSize, imageNamed imageName: String) -> SKTexture? {
    var texture: SKTexture?

    UIGraphicsBeginImageContext(size)
    let context = UIGraphicsGetCurrentContext()

    if let image = UIImage(named: imageName), let cgImage = image.cgImage {
        context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height), byTiling: true)

        if let tiledImage = UIGraphicsGetImageFromCurrentImageContext() {
            texture = SKTexture(image: tiledImage)
        }
    }

    UIGraphicsEndImageContext()

    return texture
}