ios - 如何在边缘为白色的正方形内绘制完整的 UIImage

标签 ios objective-c uiimage

您好,就像我在标题中所说的那样,我正在尝试在与 UIImage 的最大尺寸相匹配的正方形内绘制完整的 UIImage。我的问题是我怎样才能让我的代码工作。我的代码所做的是裁剪成正方形大小。我是 IO 的新手,任何人都可以提供帮助。

PS 我需要调用 CGcontext 的方法。

谢谢。

- (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
    CGSize size = [source size];
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGSize resizedImageSize;
    if (width < height) {
        resizedImageSize = CGSizeMake(height, height);
    }else {
        resizedImageSize = CGSizeMake(width, width);
    }
    UIGraphicsBeginImageContext(resizedImageSize);
    CGRect rect = CGRectMake(0, 0, resizedImageSize.width, resizedImageSize.height);
    [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
    CGContextStrokeRect(context, rect);
    UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return testImg;
}

我正在寻找的结果类型。

enter image description here

最佳答案

在 swift 3 中

extension UIImage {

    func squareMe() -> UIImage {

        var squareImage = self
        let maxSize = max(self.size.height, self.size.width)
        let squareSize = CGSize(width: maxSize, height: maxSize)

        let dx = CGFloat((maxSize - self.size.width) / 2)
        let dy = CGFloat((maxSize - self.size.height) / 2)

        UIGraphicsBeginImageContext(squareSize)
        var rect = CGRect(x: 0, y: 0, width: maxSize, height: maxSize)

        if let context = UIGraphicsGetCurrentContext() {
            context.setFillColor(UIColor.clear.cgColor)
            context.fill(rect)

            rect = rect.insetBy(dx: dx, dy: dy)
            self.draw(in: rect, blendMode: .normal, alpha: 1.0)

            if let img = UIGraphicsGetImageFromCurrentImageContext() {
                squareImage = img
            }
            UIGraphicsEndImageContext()

        }

        return squareImage
    }

}

关于ios - 如何在边缘为白色的正方形内绘制完整的 UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33404051/

相关文章:

iphone - 绘制到 quartz 上下文时,UIImage可拉伸(stretch)ImageWithLeftCapWidth不起作用

ios - 针对不同分辨率设备的页面背景图像缩放

ios - SwiftUI TextEditor UI 测试 typeText 方法失败

ios - 带有垂直对齐图像的自定义 UITabBar

ios - 在 Xcode UI 测试中等待 30 秒

iphone - iOS兼容性

ios - 无法在 Objective-C 中使用 Swift 类

ios - GLDrawElements 崩溃程序

ios - UIImage.size 不同于像素分辨率?

IOS + 德尔福 : low memory warnings - possible memory leak with TTexture?