UIImage调整方面填充和裁剪的大小

时间:2014-08-25 03:27:15

标签: ios objective-c uiimage

我有这个代码,我拍了这张尺寸为2448x3264的照片,我需要调整大小并调整到左上角的屏幕显示。对不起我的英语谢谢

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{

    imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];

    NSLog(@"%f",imagenUsr.size.height);   //2448px
    NSLog(@"%f",imagenUsr.size.width);   //3264px


}

我需要调整到320x568宽高比以填充所拍摄图像的顶部和左侧

3 个答案:

答案 0 :(得分:11)

试试这个:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];
    double width = imagenUsr.size.width;
    double height = imagenUsr.size.height;
    double screenWidth = self.view.frame.size.width;
    double apect = width/height;
    double nHeight = screenWidth/ apect;
    self.imgView.frame = CGRectMake(0, 0, screenWidth, nHeight);
    self.imgView.center = self.view.center;
    self.imgView.image = imagenUsr;
}

这将帮助您像以前一样保持纵横比。

另一种方式是:

self.imgView.contentMode = UIViewContentModeScaleAspectFit;
self.imgView.image = imagenUsr;

希望这会有所帮助.. :)

答案 1 :(得分:3)

编辑:不确定我是否错过了这个或它已被编辑,但我没有看到你想要裁剪它。拉沙德的解决方案应该适合你。

您是否尝试过使用图片创建图片视图并将其添加到视图中?

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    imagenUsr = [info objectForKey:UIImagePickerControllerOriginalImage];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
    imageView.image = imagenUsr;
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self.view addSubview:imageView];
}

答案 2 :(得分:3)

Swift 3.0 / 4.0

根据UIImageview帧大小,AspectFill图像裁剪/调整大小...。

    func ResizeImage(with image: UIImage?, scaledToFill size: CGSize) -> UIImage? {
    let scale: CGFloat = max(size.width / (image?.size.width ?? 0.0), size.height / (image?.size.height ?? 0.0))
    let width: CGFloat = (image?.size.width ?? 0.0) * scale
    let height: CGFloat = (image?.size.height ?? 0.0) * scale
    let imageRect = CGRect(x: (size.width - width) / 2.0, y: (size.height - height) / 2.0, width: width, height: height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    image?.draw(in: imageRect)
    let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}