iOS 给UIImage添加边框(直接加在UIImage上)

来源:互联网 发布:标书制作软件 编辑:程序博客网 时间:2024/05/08 00:10

先上代码。后面附上解释:

class func imageWith(radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor, image: UIImage, resultImageSize: CGSize = CGSize.zero, centerIconSize: CGSize) -> UIImage? {        var size = CGSize.zero        if resultImageSize == CGSize.zero {            size = CGSize(width: image.size.width+2*borderWidth, height: image.size.height+2*borderWidth)        }else {            size = CGSize(width: resultImageSize.width+2*borderWidth, height: resultImageSize.height+2*borderWidth)        }        UIGraphicsBeginImageContextWithOptions(size, false, 0)        let path = UIBezierPath(roundedRect: CGRect(origin: CGPoint.zero, size: size), cornerRadius: radius+borderWidth/2)        borderColor.set()        path.addClip()        path.stroke()        let clipPath = UIBezierPath(roundedRect: CGRect(x: borderWidth, y: borderWidth, width: size.width-2*borderWidth, height: size.height-2*borderWidth), cornerRadius: radius)        clipPath.addClip()        image.draw(in: CGRect(origin: CGPoint(x: borderWidth+(size.width-2*borderWidth-centerIconSize.width)/2, y: borderWidth+(size.height-2*borderWidth-centerIconSize.height)/2), size: centerIconSize))        let newImage = UIGraphicsGetImageFromCurrentImageContext()        UIGraphicsEndImageContext()        return newImage    }

具体实现思路:

1.假设边框宽度为borderWidth

2.开启的图片上下文的尺寸就应该是原始图片的宽高分别加上两倍的borderWidth,这样开启的目的是为了不让原始图片变形.

3.在上下文上面添加一个圆形填充路径.位置从0,0点开始,宽高和上下文尺寸一样大.设置颜色为要设置的边框颜色.

4.继续在上下文上面添加一个圆形路径,这个路径为裁剪路径.

  它的x,y分别从borderWidth这个点开始.宽度和高度分别和原始图片的宽高一样大.

  将绘制的这个路径设为裁剪区域.

5.把原始路径绘制到上下文当中.绘制的位置和是裁剪区域的位置相同,x,y分别从border开始绘制.

6.从上下文状态当中取出图片.

7.关闭上下文状态.