繁体   English   中英

在 Xamarin iOS C# 中将 Swift 图形代码转换为 UIKit

[英]Convert Swift graphics code to UIKit in Xamarin iOS C#

我需要在我的 Xamarin 应用程序中将图像裁剪为一个圆圈。 这是平台相关的,所以它必须使用 UIKit。

我找到了以下 Swift 代码(信用Cut a UIImage into a circle<\/a> ):

extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    var breadthRect: CGRect  { .init(origin: .zero, size: breadthSize) }
    var circleMasked: UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = false
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIBezierPath(ovalIn: breadthRect).addClip()
            UIImage(cgImage: cgImage, scale: format.scale, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}

对于圆形图像,我建议使用 - FFImageLoading<\/a>

"

没有任何建议,所以尽我所能,我整理了一个可行的版本:

public UIImage cropToCircle(UIImage inimg) {
            if(null == inimg) return null;
            // 1. clip to square:
            var length = Math.Min(inimg.Size.Width, inimg.Size.Height); 
            var x = inimg.Size.Width/2 - length/2;
            var y = inimg.Size.Height/2 - length/2;
            var cropRect = new CGRect(x, y, length, length);

            UIGraphics.BeginImageContextWithOptions(cropRect.Size, false, 0);
            var context = UIGraphics.GetCurrentContext();

            context.TranslateCTM(0.0f, (float)length);
            context.ScaleCTM(1.0f, -1.0f);
            context.DrawImage(new RectangleF(0, 0,
                (float)length, (float)length), inimg.CGImage);
            context.ClipToRect(cropRect);

            var croppedImage = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            // 2. clip to cirle 
            UIImageView imageView = new UIImageView(croppedImage);
            var layer = imageView.Layer;
            layer.MasksToBounds = true;
            layer.CornerRadius = 
                (nfloat)(Math.Min(imageView.Frame.Height, imageView.Frame.Width)) / 2;
            UIGraphics.BeginImageContext(imageView.Bounds.Size);
            layer.RenderInContext(UIGraphics.GetCurrentContext());
            var circleImg = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return circleImg;
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM