コード例 #1
0
        public object GetImageFromUri(FileUri imageUri, int targetWidth, int targetHeight, int rotation)
        {
            using (Stream stream = GetFileSystem().OpenFile(imageUri, UniversalFileMode.Open, UniversalFileAccess.Read, UniversalFileShare.Read))
            {
                CGImageSource source = CGImageSource.FromUrl(imageUri.ToNSUrl());

                CGImageOptions options = new CGImageOptions();
                options.ShouldCache = false;

                var props = source.CopyProperties(options, 0);

                int imageWidth  = ((NSNumber)props["PixelWidth"]).Int32Value;
                int imageHeight = ((NSNumber)props["PixelHeight"]).Int32Value;

                int scale = 1;
                while (imageWidth / scale / 2 >= (nfloat)targetWidth &&
                       imageHeight / scale / 2 >= (nfloat)targetHeight)
                {
                    scale *= 2;
                }

                stream.Seek(0, SeekOrigin.Begin);
                UIImage image = UIImage.LoadFromData(NSData.FromUrl(imageUri.ToNSUrl()), scale);

                if (rotation != 0)
                {
                    float radians = rotation * (float)Math.PI / 180f;

                    CGRect            imageFrame = new CGRect(0, 0, image.Size.Width, image.Size.Height);
                    CGAffineTransform t          = CGAffineTransform.MakeRotation(radians);
                    imageFrame = t.TransformRect(imageFrame);

                    CGSize rotatedSize = new CGSize(imageFrame.Width, imageFrame.Height);

                    UIGraphics.BeginImageContext(rotatedSize);

                    using (CGContext context = UIGraphics.GetCurrentContext())
                    {
                        context.TranslateCTM(rotatedSize.Width / 2, rotatedSize.Height / 2);
                        context.RotateCTM(-radians);
                        context.ScaleCTM(1.0f, -1.0f);
                        image.Draw(new CGRect(-image.Size.Width / 2, -image.Size.Height / 2, image.Size.Width, image.Size.Height));

                        image = UIGraphics.GetImageFromCurrentImageContext();
                    }

                    UIGraphics.EndImageContext();
                }

                return(image);
            }
        }