iphone sdk按钮与图像

时间:2011-07-29 07:12:46

标签: iphone uibutton

我正在试图弄清楚如何执行以下操作:

我有一个按钮,它有一个图像而不是默认的外观。用户单击按钮并选择照片(使用图像选择器)。我想将照片的图像设置为用户点击的照片。

所以,我做了以下几点:

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

不幸的是,这会将图像缩放到小盒子中。确保图像被按钮的边框裁剪而不是缩放到图像中的最佳方法是什么?

编辑:想要注意我目前在模拟器上。

2 个答案:

答案 0 :(得分:1)

您可以使用此功能创建一个裁剪版本,将按钮的高度和宽度作为参数传递

- (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;
}

答案 1 :(得分:0)

你设置为

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