我需要翻转和图像,然后将其添加到按钮。我使用了以下代码
UIButton *playButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
playButton.frame = CGRectMake(xing, ying, dx,dy);
[playButton setTitle:text forState:UIControlStateNormal];
[playButton addTarget:self action:function forControlEvents:UIControlEventTouchUpInside];
UIImage *buttonImageNormal = [UIImage imageNamed:@"Begin-Set-Button.png"];
UIImage * other = [UIImage imageWithCGImage:buttonImageNormal.CGImage
scale:1.0 orientation: UIImageOrientationUpMirrored];
UIImage * awesome = [other stretchableImageWithLeftCapWidth:12 topCapHeight:0];
[playButton setBackgroundImage:awesome forState:UIControlStateNormal];
它正确显示图像,但当我点击它时,按钮显示未打开的图像。
在我尝试修复此问题时,我添加了以下代码行
[playButton setBackgroundImage:awesome forState:UIControlStateHighlighted];
然而,当我点击按钮时,它不会像我使用未打开的图像创建的按钮那样使颜色变暗。
如何对其进行编码,以便在使用翻转图像时显示翻转后的图像变暗?我知道如何手动使图像变暗,但我想知道是否有办法通过简单的函数调用自动完成它?
答案 0 :(得分:3)
而不是翻转图像。您是否尝试过翻转imageView?
UIImage *img = [UIImage imageNamed:@"path/to-image.png"];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.imageView.transform = CGAffineTransformMakeRotation(M_PI); // flip the image view
[button setImage:img forState:UIControlStateNormal];
这就是我所做的,以保持选择状态突出显示而不必处理图像翻转。
答案 1 :(得分:1)
我也有同样的问题,所以我搜索了这篇文章。我怀疑图像可能没有“固化”,因此镜像操作不是永久性的。
签出“imageWithCGImage:”的文档显示以下内容:
<强>讨论强> 此方法不会缓存图像对象。您可以使用Core Graphics框架的方法创建Quartz图像引用。
因此,除非在新的上下文中创建新图像,否则图像的镜像不适用于事件。我也一直在研究一种在任意大小的画布上绘制图像的方法,以创建具有相同背景的按钮。您可以使用此方法创建维护CG操作的图像,例如镜像:
+ (UIImage *)imageWithCanvasSize:(CGSize)canvasSize withImage:(UIImage *)anImage
{
if (anImage.size.width > canvasSize.width ||
anImage.size.height > canvasSize.height)
{
// scale image first
anImage = [anImage scaleWithAspectToSize:canvasSize];
}
CGRect targetRect = CGRectZero;
CGFloat xOrigin = (canvasSize.width - anImage.size.width) / 2;
CGFloat yOrigin = (canvasSize.height - anImage.size.height) / 2;
targetRect.origin = CGPointMake(xOrigin, yOrigin);
targetRect.size = anImage.size;
UIGraphicsBeginImageContextWithOptions(canvasSize, NO, anImage.scale);
[anImage drawInRect:targetRect];
UIImage *canvasedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return canvasedImage;
}
- (UIImage*)scaleWithAspectToSize:(CGSize)newSize
{
CGSize scaledSize = newSize;
float scaleFactor = 1.0;
if (self.size.width > self.size.height)
{
scaleFactor = self.size.width / self.size.height;
scaledSize.width = newSize.width;
scaledSize.height = newSize.height / scaleFactor;
}
else
{
scaleFactor = self.size.height / self.size.width;
scaledSize.height = newSize.height;
scaledSize.width = newSize.width / scaleFactor;
}
UIGraphicsBeginImageContextWithOptions(scaledSize, NO, 0.0);
CGRect scaledImageRect = CGRectMake(0.0, 0.0, scaledSize.width, scaledSize.height);
[self drawInRect:scaledImageRect];
UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}