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

这段代码按照我的预期在顶部和左侧添加了边框,但是在底部和右侧则剪切了我的图像。那么,谁知道一个问题呢?

最佳答案

您正在创建一个由输入参数确定大小的上下文,然后在其中绘制图像,其宽度和高度由边框大小缩减。相反,您应该创建上下文大小以解决所需的间隙,然后以其正常大小偏移边框大小绘制图像。

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
}

08-28 13:01