Cropping center square of UIImage

后端 未结 18 637
日久生厌
日久生厌 2020-12-07 23:09

So here\'s where I\'ve made it so far. I am using a UIImage captured from the camera and can crop the center square when in landscape. For some reason this doesn\'t transl

18条回答
  •  情歌与酒
    2020-12-07 23:39

    Xamarin:

    UIImage ImageByCroppingImage(UIImage image, CGSize size)
    {
        double newCropWidth, newCropHeight;
    
        if (image.Size.Width < image.Size.Height)
        {
            newCropWidth = image.Size.Width < size.Width ? size.Width : image.Size.Width;
            newCropHeight = (newCropWidth * size.Height) / size.Width;
        }
        else
        {
            newCropHeight = image.Size.Height < size.Height ? size.Height : image.Size.Height;
            newCropWidth = (newCropHeight * size.Width) / size.Height;
        }
    
        double x = image.Size.Width / 2.0 - newCropWidth / 2.0;
        double y = image.Size.Height / 2.0 - newCropHeight / 2.0;
    
        CGRect cropRect = new CGRect(x, y, newCropWidth, newCropHeight);
        var imageRef = image.CGImage.WithImageInRect(cropRect);
    
        var cropped = new UIImage(imageRef);
    
        return cropped;
    }
    

提交回复
热议问题