在 UIButton 上使用 LSR 图像

Using an LSR image on a UIButton

我正在创建一个 tvOS 应用程序,我想在几个按钮上使用视差图像。来自 the docs:

To incorporate parallax images in your app:

  1. Create a UIImage object.
  2. You load the image differently depending on whether the image is included in your app bundle or whether you have downloaded the image.
    • Bundle—Load images using imageNamed:.
    • Downloaded file—Load images using imageWithContentsOfFile:.
  3. Create a new UIImageView object using the loaded images.
  4. If the UIImageView is part of another view, set adjustsImageWhenAncestorFocused to YES on the UIImageView.

我知道上面写的是 UIImageView,但我希望在 UIButton 上实现相同的效果,例如主屏幕应用程序图标。

我已经创建了艺术品,在资产目录中制作了一个堆栈,并使用 imageNamed: 加载了图像,但是 UIButton 的行为不像视差图像。它不像主屏幕图标那样左右摇摆。它看起来只是一个平面图像。

为了使 UIButton 的行为像主屏幕应用程序图标一样,我还必须启用其他功能吗?

UIButton* quitGame = [[UIButton alloc] initWithFrame:rectWithNewX(playAgain.frame, 985)];
[quitGame setImage:[UIImage imageNamed:@"quit.lsr"] forState:UIControlStateNormal];
[quitGame setAdjustsImageWhenHighlighted:YES];
fadeIn(quitGame, self.view, 0.5);

截至目前,仅使用 UIButton 是不可能的,但是,我确实找到了解决方法。

相反,创建一个 UIImageView 来填充 UIButton 的大小并使其成为 UIButton 的子视图。然后调用 adjustsImageWhenAncestorFocused: 并将其设置为 true。瞧!

UIButton* playAgain = [[UIButton alloc] initWithFrame:CGRectMake(centerX(650, self.view), sh() - 250, 300, 180)];
[playAgain setAdjustsImageWhenHighlighted:YES];
[playAgain addTarget:self action:@selector(playAgain) forControlEvents:UIControlEventPrimaryActionTriggered];
fadeIn(playAgain, self.view, 0.5);

UIImageView* playAgainIGV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 180)];
[playAgainIGV setImage:[UIImage imageNamed:@"playagain.lsr"]];
[playAgainIGV setAdjustsImageWhenAncestorFocused:YES];
[playAgain addSubview:playAgainIGV];

我在设置文件或预编译 LSR 时遇到问题。

通过 Asset Catalog -> New Apple TV Image Stack 在 XCode Asset Catalog 中创建 LSR 并拖入 PNG,然后通过 Interface Builder 或通过此作品设置图像:

-(void) setLsr:(UIButton *)button lsrNamed:(NSString *)lsr {
    [button setAdjustsImageWhenHighlighted:YES];

    UIImageView *biv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
    [biv setImage:[UIImage imageNamed:lsr]];
    [biv setAdjustsImageWhenAncestorFocused:YES];
    [button addSubview:biv];
}

关于的回答我做了一个简单的Swift方法来创建一个视差效果按钮 :

func createParallaxButton(button: UIButton, imageNamed: String) {
        button.adjustsImageWhenHighlighted = true
        let buttonBg = UIImageView(image: UIImage(named: imageNamed))
        buttonBg.adjustsImageWhenAncestorFocused = true
        buttonBg.frame = button.bounds
        button.addSubview(buttonBg)
    }
createParallaxButton(myButton, imageNamed: "myButtonimage.lsr")