UIImage: Resize, then Crop

后端 未结 16 2489
夕颜
夕颜 2020-11-22 11:51

I\'ve been bashing my face into this one for literally days now and even though I feel constantly that I am right on the edge of revelation, I simply cannot achieve my goal.

16条回答
  •  旧巷少年郎
    2020-11-22 12:11

    Xamarin.iOS version for accepted answer on how to resize and then crop UIImage (Aspect Fill) is below

        public static UIImage ScaleAndCropImage(UIImage sourceImage, SizeF targetSize)
        {
            var imageSize = sourceImage.Size;
            UIImage newImage = null;
            var width = imageSize.Width;
            var height = imageSize.Height;
            var targetWidth = targetSize.Width;
            var targetHeight = targetSize.Height;
            var scaleFactor = 0.0f;
            var scaledWidth = targetWidth;
            var scaledHeight = targetHeight;
            var thumbnailPoint = PointF.Empty;
            if (imageSize != targetSize)
            {
                var widthFactor = targetWidth / width;
                var heightFactor = targetHeight / height;
                if (widthFactor > heightFactor)
                {
                    scaleFactor = widthFactor;// scale to fit height
                }
                else
                {
                    scaleFactor = heightFactor;// scale to fit width
                }
                scaledWidth = width * scaleFactor;
                scaledHeight = height * scaleFactor;
                // center the image
                if (widthFactor > heightFactor)
                {
                    thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
                }
                else
                {
                    if (widthFactor < heightFactor)
                    {
                        thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
                    }
                }
            }
            UIGraphics.BeginImageContextWithOptions(targetSize, false, 0.0f);
            var thumbnailRect = new RectangleF(thumbnailPoint, new SizeF(scaledWidth, scaledHeight));
            sourceImage.Draw(thumbnailRect);
            newImage = UIGraphics.GetImageFromCurrentImageContext();
            if (newImage == null)
            {
                Console.WriteLine("could not scale image");
            }
            //pop the context to get back to the default
            UIGraphics.EndImageContext();
    
            return newImage;
        }
    

提交回复
热议问题