Draw border around content of UIImageView

前端 未结 2 511
我在风中等你
我在风中等你 2020-12-29 11:48

I\'ve a UIImageView with a image with is a car with a transparent background:

\"enter<

2条回答
  •  一向
    一向 (楼主)
    2020-12-29 12:28

    Here's what I did:

    I did it in Swift just to check it in playgrounds, think you can translate it to Objective-C easily:

    import UIKit
    
    
    func drawOutlie(#image:UIImage, color:UIColor) -> UIImage
    {
      var newImageKoef:CGFloat = 1.08
    
      var outlinedImageRect = CGRect(x: 0.0, y: 0.0, width: image.size.width * newImageKoef, height: image.size.height * newImageKoef)
    
      var imageRect = CGRect(x: image.size.width * (newImageKoef - 1) * 0.5, y: image.size.height * (newImageKoef - 1) * 0.5, width: image.size.width, height: image.size.height)
    
      UIGraphicsBeginImageContextWithOptions(outlinedImageRect.size, false, newImageKoef)
    
      image.drawInRect(outlinedImageRect)
    
      var context = UIGraphicsGetCurrentContext()
      CGContextSetBlendMode(context, kCGBlendModeSourceIn)
    
      CGContextSetFillColorWithColor(context, color.CGColor)
      CGContextFillRect(context, outlinedImageRect)
      image.drawInRect(imageRect)
    
      var newImage = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
    
      return newImage
    
    }
    
    var imageIn = UIImage(named: "158jM")
    
    var imageOut = drawOutlie(image: imageIn, UIColor.redColor())
    

    So how does it work?

    1. We create clean context (aka canvas) with a bit bigger size then original image (for outline)
    2. We draw our image on whole canvas
    3. We fill that image with color
    4. We draw smaller image on top

    You can change outline size changing this property : var newImageKoef:CGFloat = 1.08

    Here's a result that I had in playgrounds

    enter image description here

提交回复
热议问题