Ringo Blancke
Ringo Blancke

Reputation: 2444

iphone sdk button with image

I'm trying to figure out how to do the following:

I have a button that has an image instead of the default look. User clicks button and chooses a photo (using image picker). I want to set the image of the photo to the photo that the user has clicked.

so, I do the following:

[self.activeBtn setImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] forState:UIControlStateNormal];

Unfortunately, this scales the image into the little box. What is the best way to ensure that the image is cropped by the borders of the button instead of getting scaled into it?

Edit: want to note that I'm currently on the simulator.

Upvotes: 0

Views: 1402

Answers (2)

Bushra Shahid
Bushra Shahid

Reputation: 3579

You can use this function to create a cropped version passing the height and width of button as arguments

- (UIImage*)thumbnailOfHeight:(int)height andWidth:(int)width fromImage:(UIImage*)image{
    UIImage *thumbnail;

    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];                                  

    BOOL isWidthGreaterThanHeight = (image.size.width > image.size.height);
    float sideFull = (isWidthGreaterThanHeight)? image.size.height : image.size.width;

    CGRect clippedRect = CGRectMake(0, 0, sideFull, sideFull);

    UIGraphicsBeginImageContext(CGSizeMake(height, width));
    CGContextRef currentContext = UIGraphicsGetCurrentContext();

    CGContextClipToRect(currentContext, clippedRect);

    CGFloat scaleFactor = width/sideFull;

    if (isWidthGreaterThanHeight) {
        CGContextTranslateCTM(currentContext, -((image.size.width - sideFull)/2)*scaleFactor, 0);
    }
    else {
        CGContextTranslateCTM(currentContext,0, -((image.size.height - sideFull)/2)*scaleFactor);
    }
    CGContextScaleCTM(currentContext, scaleFactor, scaleFactor);

    [imageView.layer renderInContext:currentContext];
    thumbnail = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();
    [imageView release];
    return thumbnail;
}

Upvotes: 1

EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 2707

You set like

 [self.activeBtn setBackgroundImage:[info objectForKey:@"UIImagePickerControllerOriginalImage"] forState:UIControlStateNormal];

Upvotes: 0

Related Questions