开发者

CGRect image resizing

开发者 https://www.devze.com 2023-01-14 01:32 出处:网络
I\'m using CG开发者_如何学CRect to display an image. I\'d like the CGRect to use the width and height of the image without me specifying it.

I'm using CG开发者_如何学CRect to display an image. I'd like the CGRect to use the width and height of the image without me specifying it.

can this:

CGRectMake(0.0f, 40.0f, 480.0f, 280.0f);

become this:

CGRectMake(0.0f, 40.0f, myImage.width, myImage.height);

some images get distorted when I specify the parameters.

here's the code:

CGRect myImageRect = CGRectMake(0.0f, 40.0f, 480.0f, 280.0f);
UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];
[myImage setImage:[UIImage imageNamed:recipe.img]];

thanks for any help.


Once you have a UIImage, you can find its size by looking at the size property:

UIImage * image = [UIImage imageNamed:recipe.img];
CGRect rect = CGRectMake(0.0f, 40.0f, image.size.width, image.size.height);

UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect];
[imageView setImage:image];


This category on UIImage might be helpful.

Use it like this: aImage =[aImage imageByScalingProportionallyToSize: myImageRect]

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

    UIImage *sourceImage = self;
    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor < heightFactor) 
            scaleFactor = widthFactor;
        else
            scaleFactor = heightFactor;

        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image

//        if (widthFactor < heightFactor) {
//          thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
//        } else if (widthFactor > heightFactor) {
//          thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
//        }

        //thumbnailPoint.x
    }


    // this is actually the interesting part:

    UIGraphicsBeginImageContext(targetSize);

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if(newImage == nil) NSLog(@"could not scale image");


    return newImage ;
}

@end;
0

精彩评论

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