【问题标题】:Swift iOS add invisible border for UIImageSwift iOS 为 UIImage 添加隐形边框
【发布时间】:2014-07-22 08:39:12
【问题描述】:

我正在编写自己的键盘,我需要按钮彼此保持距离,所以我需要为我的 UIImage 添加不可见的边框,所以这是我的代码

func imageWithBorderForImage(initalImage: UIImage, withWidth width: CGFloat, withHeight height: CGFloat) -> UIImage {
        UIGraphicsBeginImageContext(CGSizeMake(width , height));
        initalImage.drawInRect(CGRectMake(borderSize, borderSize, width - borderSize * 2, height - borderSize));
        let resultedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return resultedImage
    }

此代码按我的预期在顶部和左侧添加边框,但在底部和右侧它会剪切我的图像。那么哪里出了问题谁知道呢?

【问题讨论】:

    标签: ios uiimage swift border


    【解决方案1】:

    您正在创建一个由输入参数调整大小的上下文,然后在其中绘制图像,其宽度和高度根据您的边框大小裁剪。相反,您应该创建大小以考虑所需间隙的上下文,然后以边框大小偏移的正常大小绘制图像。

    func imageWithBorderForImage(initalImage: UIImage) -> UIImage {
        UIGraphicsBeginImageContext(CGSizeMake(initalImage.size.width + borderSize * 2.0, initalImage.size.height + borderSize * 2.0))
    
        initalImage.drawInRect(CGRectMake(borderSize, borderSize, initalImage.size.width, initalImage.size.height))
        let resultedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    
        return resultedImage
    }
    

    【讨论】:

    • @user3417231 抱歉,输入的大小一定不是我想的那样。我已经更新了我的代码以使其更加清晰。我已经对此进行了测试,并且效果很好。
    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多