ios - UIButton 在突出显示状态下更改代码中创建的图像

标签 ios objective-c uibutton uiimage uikit

我有两个按钮。它们都有相同的图像,只是其中一张图像被翻转了。如果可以以编程方式创建图像,我不想在我的应用程序包中包含多余的图像,因此我创建了如下按钮:

UIImage *forwardImage = [UIImage imageNamed:rewind_btn_img];
UIImage *rewindImage  = [UIImage imageWithCGImage:forwardImage.CGImage
                                            scale:forwardImage.scale
                                      orientation:UIImageOrientationUpMirrored];

NSArray *images = @[rewindImage, forwardImage];

for (int i = 0; i < 2; i++)
{
    UIButton *btn   = [UIButton buttonWithType:UIButtonTypeCustom];
    UIImage  *image = images[i];
    btn.frame       = CGRectMake(0.f, 0.f, image.size.width, image.size.height);
    btn.center      = CGPointMake(self.playButton.center.x + (i == 0 ? - 80.f : 80.f) * TGScaleMultiplier, self.playButton.center.y);
    btn.tag         = i + 1;
    [btn setBackgroundImage:image forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(rewindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btn];
}

问题是,当我按下图像为 rewindImage 的按钮时,它会显示原始图像,翻转到另一侧。我在这里做错了什么吗?有什么解决办法吗?

最佳答案

不确定为什么 UIImage:imageWithCGImage 不稳定,但我尝试了另一种镜像图像的方法,当应用于按钮时效果很好。因此,摆脱 UIImage:imageWithCGImage 行并使用它:

UIImage *rewindImageBase = [UIImage imageNamed:rewind_btn_img];
UIGraphicsBeginImageContext(rewindImageBase.size);
CGContextRef current_context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(current_context, rewindImageBase.size.width, 0);
CGContextScaleCTM(current_context, -1.0, 1.0);
[rewindImageBase drawInRect:CGRectMake(0, 0, rewindImageBase.size.width, rewindImageBase.size.height)];
UIImage *rewindImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

应该可以了。

关于ios - UIButton 在突出显示状态下更改代码中创建的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615115/

相关文章:

swift - 如何使 UIButton 具有正确的图像和文本外观?

objective-c - 存储应用程序范围的实例

ios - 单击 Swift XCode 中的编程按钮后如何在 Controller 之间切换

ios - Xamarin iOS 为 KeyChain 增加了值(value),设备上的所有应用程序都可以访问它

ios - 使用 Google 标签管理器阻止 firebase 事件 | iOS

ios - 如何使用自定义类在 UITextField 的左侧添加图像

objective-c - 仅允许给定核心数据实体的一个实例

ios - 触摸一次后如何使 UIButton 不可点击并隐藏和取消隐藏按钮? - swift

ios - 添加自定义 Segues 后 UITableView 在屏幕上的偏移量

ios - 类型 '[NSObject : AnyObject]!' 不符合协议(protocol) 'DictionaryLiteralConvertible'