缩放UIImage以正确适合UIImageView

时间:2017-09-07 13:16:20

标签: ios objective-c uiimageview uiimage

我有以下代码,使用UIImagePickerController

获取图片形式的照片库
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *pickerImg = info[UIImagePickerControllerEditedImage];
    if (pickerImg == nil) {
        pickerImg = info[UIImagePickerControllerOriginalImage];
    }

    NSData *imageData = UIImagePNGRepresentation(pickerImg);
    UIImage *img = [UIImage imageWithData:imageData];

    UIImage *fixedOrientationImage = [UIImage imageWithCGImage:img.CGImage scale:pickerImg.scale orientation:pickerImg.imageOrientation];
    pickerImg = fixedOrientationImage;

    cropView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,  self.view.bounds.size.height)];
    cropView.backgroundColor = [UIColor darkTextColor];

    [self.navigationController setNavigationBarHidden:YES animated:YES];

    UIImageView * cropImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,  self.view.bounds.size.height - 60)];
    cropImageView.image = pickerImg;
    cropImageView.contentMode = UIViewContentModeScaleAspectFit;
    cropImageView.clipsToBounds = YES;

    [cropView addSubview:cropImageView];
    [self.view addSubview:cropView];
}

我选择了以下图片

enter image description here

显示在cropImageView之上

enter image description here

1 个答案:

答案 0 :(得分:2)

设置内容模式后尝试设置图像或帧

UIImageView * cropImageView = [[UIImageView alloc] init];
cropImageView.contentMode = UIViewContentModeScaleAspectFit;
cropImageView.frame = CGRectMake(0, 0, self.view.bounds.size.width,  self.view.bounds.size.height - 60);
cropImageView.image = pickerImg;
cropImageView.clipsToBounds = YES;