开发者

How do i get it to scale my UIimage to a different size?

I have an image formed by a number of sublayers on a UIView, and then it takes a screenshot as so:

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

Then it puts it onto a button:

[objectButton setImage:screenShot forState:UIControlStateNormal];

But the image displays at it's own size, so if the button isn't the same size as the imag开发者_运维问答e then i have a problem of it not making the image bigger or smaller.

How can i get it to change the size of the image to the size of the button?


Try this category -

.h file -

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

.m file -

@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

you can call it like this -

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

Hope it help!


Try Like this,

[objectButton setBackgroundImage:screenShot forState:UIControlStateNormal];


You can change the contentMode on the UIButton to scale to fit. This will adjust the size of the image to not be larger than the bounds of the button. Also set the image as the background Image of the button instead of the image.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜