2011-05-16 14 views
1

我有由多个上一个UIView子层形成的图像,然后将其采用的屏幕截图为这样:我如何获得它来缩放我的UIimage到不同的大小?

UIGraphicsBeginImageContext(object.bounds.size); 
     [object.layer renderInContext:UIGraphicsGetCurrentContext()]; 
     UIImage *screenShot = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 

然后它把它放到一个按钮:

[objectButton setImage:screenShot forState:UIControlStateNormal]; 

但图像以它自己的尺寸显示,所以如果按钮与图像尺寸不一样,那么我有一个问题,它不会使图像变大或变小。

我怎样才能得到它的图像大小更改为按钮的大小?

回答

2

尝试这一类 -

.h文件中 -

@interface UIImage (UIImageAdditions) 
- (UIImage*)scaleToSize:(CGSize)size; 
@end 

.m文件 -

@implementation UIImage (UIImageAdditions) 

- (UIImage*)scaleToSize:(CGSize)size { 
    UIGraphicsBeginImageContext(size); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextTranslateCTM(context, 0.0, size.height); 
    CGContextScaleCTM(context, 1.0, -1.0); 

    CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage); 

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return scaledImage; 
} 

@end 

你可以这样调用 -

[imageObject scaleToSize:CGSizeMake(weight, height)]; 

希望它能帮助!

0

您可以更改UIButton上的contentMode以适合缩放。这将调整图像的大小,使其不大于按钮的边界。还要将图像设置为按钮的背景图像而不是图像。

objectButton.contentMode = UIViewContentModeScaleAspectFit; 
[objectButton setBackgroundImage:image forStage:UIControlStateNormal]; 
+0

感谢您的帮助,但仍然显示与以前相同。 – Andrew 2011-05-16 01:49:02

0

尝试这样,

[objectButton setBackgroundImage:screenShot forState:UIControlStateNormal]; 
相关问题