Swift iOS为UIImage添加了隐形边框

时间:2014-07-22 08:39:13

标签: ios uiimage swift border

我正在编写自己的键盘,我需要按钮相互之间的距离,所以我需要为我的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
    }

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

1 个答案:

答案 0 :(得分: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
}