首页 > 解决方案 > 无法让 SKSpriteNode 的 centerRect 属性工作

问题描述

很简单。我按照 Apple 文档中的描述设置了我的 sprite 的 centerRect,但是它显示的图像被扭曲了(因为我没有定义 centerRect 属性)。我的代码:

let sprite = SKSpriteNode()
sprite.texture = SKTexture(imageNamed: "ImageName")
sprite.centerRect = CGRect(x: 0.49, y: 0.49, width: 0.02, height: 0.02)
sprite.scale(to:CGSize(width: myCustomWidth, height: myCustomHeight))
//sprite.size = CGSize(width: myCustomWidth, height: myCustomHeight)

我不知道我在哪里犯了错误,或者我的代码中是否缺少某些东西。

这是它的样子

这就是我要的

先感谢您。

标签: iosswiftsprite-kitskspritenodestretch

解决方案


取决于宽度和高度是什么,对应物应该扭曲。中心部分仅为图像的 2% * 2%,是缩放操作中主要的缩放部分。

你可以成像四个角不会改变,所以如果缩放到原始图像的(2X * 2X),即从(0.02 * 0.02 -> 1.02 * 1.02),中心部分会失真很多,即超过2500倍失真在图像的中心。

你的代码没有问题。

到目前为止,这个概念是正确的。如果你不能得到你想要的,可能是你原始图像大小的大小。

sprite.texture = SKTexture(imageNamed: "ImageName")
print (sprite.texture?.size()) // If size is very large here, then you cannot get what you want. The size of image should be small than target.  Actually only when you zoom in the texture, i.e, the current size is smaller than CGSize(width: myCustomWidth, height: myCustomHeight), you may get the result.

sprite.centerRect = CGRect(x: 0.49, y: 0.49, width: 0.02, height: 0.02)
sprite.scale(to:CGSize(width: myCustomWidth, height: myCustomHeight))
sprite.size = CGSize(width: myCustomWidth, height: myCustomHeight)

最后一部分是我的测试代码。

 class TestViewController: UIViewController{


        @IBOutlet weak var skview: SKView!

        override func viewDidAppear(_ animated: Bool) {
            super.viewDidAppear(animated)
            let sprite1 = SKSpriteNode()
            sprite1.texture = SKTexture(imageNamed: "round.png")
            print (sprite1.texture?.size())
            sprite1.centerRect = CGRect(x: 0.49, y: 0.49, width: 0.02, height: 0.02)
            print (sprite1.size)
            sprite1.scale(to:CGSize(width: 300, height:100))
            sprite1.size = CGSize(width: 300, height: 100)
            print (sprite1)
            skview.scene?.addChild(sprite1)
        }}

在此处输入图像描述


推荐阅读