how to add colored border to uiimage in swift










2














It is pretty easy to add border to UIImageView, using layers (borderWidth, borderColor etc.). Is there any possibility to add border to image, not to image view? Does somebody know?



Update:



I tried to follow the suggestion below und used extension. Thank you for that but I did not get the desired result. Here is my code. What is wrong?



import UIKit
class ViewController: UIViewController

var imageView: UIImageView!
var sizeW = CGFloat()
var sizeH = CGFloat()

override func viewDidLoad()
super.viewDidLoad()

sizeW = view.frame.width
sizeH = view.frame.height

setImage()


func setImage()

//add image view
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: sizeW/2, height: sizeH/2))
imageView.center = view.center
imageView.tintColor = UIColor.orange
imageView.contentMode = UIViewContentMode.scaleAspectFit

let imgOriginal = UIImage(named: "plum")!.withRenderingMode(.alwaysTemplate)
let borderImage = imgOriginal.imageWithBorder(width: 2, color: UIColor.blue)
imageView.image = borderImage

view.addSubview(imageView)








extension UIImage
func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else return nil
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result




The second image with the red border is more or less what I need:



enter image description here



enter image description here










share|improve this question























  • What exactly do you need here?
    – Dharmesh Kheni
    Dec 20 '17 at 7:47










  • I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
    – Roman
    Dec 20 '17 at 8:02











  • I added a second picture with the more or less desirable result.
    – Roman
    Dec 20 '17 at 8:10















2














It is pretty easy to add border to UIImageView, using layers (borderWidth, borderColor etc.). Is there any possibility to add border to image, not to image view? Does somebody know?



Update:



I tried to follow the suggestion below und used extension. Thank you for that but I did not get the desired result. Here is my code. What is wrong?



import UIKit
class ViewController: UIViewController

var imageView: UIImageView!
var sizeW = CGFloat()
var sizeH = CGFloat()

override func viewDidLoad()
super.viewDidLoad()

sizeW = view.frame.width
sizeH = view.frame.height

setImage()


func setImage()

//add image view
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: sizeW/2, height: sizeH/2))
imageView.center = view.center
imageView.tintColor = UIColor.orange
imageView.contentMode = UIViewContentMode.scaleAspectFit

let imgOriginal = UIImage(named: "plum")!.withRenderingMode(.alwaysTemplate)
let borderImage = imgOriginal.imageWithBorder(width: 2, color: UIColor.blue)
imageView.image = borderImage

view.addSubview(imageView)








extension UIImage
func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else return nil
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result




The second image with the red border is more or less what I need:



enter image description here



enter image description here










share|improve this question























  • What exactly do you need here?
    – Dharmesh Kheni
    Dec 20 '17 at 7:47










  • I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
    – Roman
    Dec 20 '17 at 8:02











  • I added a second picture with the more or less desirable result.
    – Roman
    Dec 20 '17 at 8:10













2












2








2


1





It is pretty easy to add border to UIImageView, using layers (borderWidth, borderColor etc.). Is there any possibility to add border to image, not to image view? Does somebody know?



Update:



I tried to follow the suggestion below und used extension. Thank you for that but I did not get the desired result. Here is my code. What is wrong?



import UIKit
class ViewController: UIViewController

var imageView: UIImageView!
var sizeW = CGFloat()
var sizeH = CGFloat()

override func viewDidLoad()
super.viewDidLoad()

sizeW = view.frame.width
sizeH = view.frame.height

setImage()


func setImage()

//add image view
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: sizeW/2, height: sizeH/2))
imageView.center = view.center
imageView.tintColor = UIColor.orange
imageView.contentMode = UIViewContentMode.scaleAspectFit

let imgOriginal = UIImage(named: "plum")!.withRenderingMode(.alwaysTemplate)
let borderImage = imgOriginal.imageWithBorder(width: 2, color: UIColor.blue)
imageView.image = borderImage

view.addSubview(imageView)








extension UIImage
func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else return nil
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result




The second image with the red border is more or less what I need:



enter image description here



enter image description here










share|improve this question















It is pretty easy to add border to UIImageView, using layers (borderWidth, borderColor etc.). Is there any possibility to add border to image, not to image view? Does somebody know?



Update:



I tried to follow the suggestion below und used extension. Thank you for that but I did not get the desired result. Here is my code. What is wrong?



import UIKit
class ViewController: UIViewController

var imageView: UIImageView!
var sizeW = CGFloat()
var sizeH = CGFloat()

override func viewDidLoad()
super.viewDidLoad()

sizeW = view.frame.width
sizeH = view.frame.height

setImage()


func setImage()

//add image view
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: sizeW/2, height: sizeH/2))
imageView.center = view.center
imageView.tintColor = UIColor.orange
imageView.contentMode = UIViewContentMode.scaleAspectFit

let imgOriginal = UIImage(named: "plum")!.withRenderingMode(.alwaysTemplate)
let borderImage = imgOriginal.imageWithBorder(width: 2, color: UIColor.blue)
imageView.image = borderImage

view.addSubview(imageView)








extension UIImage
func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else return nil
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result




The second image with the red border is more or less what I need:



enter image description here



enter image description here







ios swift image image-processing border






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 20 '17 at 8:08

























asked Dec 20 '17 at 6:46









Roman

118210




118210











  • What exactly do you need here?
    – Dharmesh Kheni
    Dec 20 '17 at 7:47










  • I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
    – Roman
    Dec 20 '17 at 8:02











  • I added a second picture with the more or less desirable result.
    – Roman
    Dec 20 '17 at 8:10
















  • What exactly do you need here?
    – Dharmesh Kheni
    Dec 20 '17 at 7:47










  • I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
    – Roman
    Dec 20 '17 at 8:02











  • I added a second picture with the more or less desirable result.
    – Roman
    Dec 20 '17 at 8:10















What exactly do you need here?
– Dharmesh Kheni
Dec 20 '17 at 7:47




What exactly do you need here?
– Dharmesh Kheni
Dec 20 '17 at 7:47












I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
– Roman
Dec 20 '17 at 8:02





I need, let say, a red border with borderWidth 3 around the plum itself and not around the image view. How could I get it?
– Roman
Dec 20 '17 at 8:02













I added a second picture with the more or less desirable result.
– Roman
Dec 20 '17 at 8:10




I added a second picture with the more or less desirable result.
– Roman
Dec 20 '17 at 8:10












4 Answers
4






active

oldest

votes


















3














Here is the way how you can achieve that:



Add below extension to your code:



extension UIImage 
func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
imageView.contentMode = .center
imageView.image = self
imageView.layer.borderWidth = width
imageView.layer.borderColor = color.cgColor
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else return nil
imageView.layer.render(in: context)
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result




And you can use it this way:



let imgOriginal = UIImage.init(named: "Richie_Rich")
img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)


And result will be:



enter image description here



Here is the original post which is with Round corners but I removed that code because you did't ask for it.






share|improve this answer




















  • I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
    – Roman
    Dec 20 '17 at 7:07











  • You already have it with above code. img.image is what you are looking for. @Roman
    – Dharmesh Kheni
    Dec 20 '17 at 7:08











  • You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
    – Dharmesh Kheni
    Dec 20 '17 at 7:17










  • Thank you Richie Rich, see my update with code above.
    – Roman
    Dec 20 '17 at 7:46


















0














Borders to the images belongs to image processing area of iOS. It's not easy as borders for a UIView, It's pretty deep but if you're willing to go the distance, here is a library and a hint for the journey
https://github.com/BradLarson/GPUImage



try using GPUImageThresholdEdgeDetectionFilter



or try OpenCV https://docs.opencv.org/2.4/doc/tutorials/ios/image_manipulation/image_manipulation.html






share|improve this answer




























    0














    Use this simple extension for UIImage



    extension UIImage 

    func outline() -> UIImage?

    UIGraphicsBeginImageContext(size)
    let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
    self.draw(in: rect, blendMode: .normal, alpha: 1.0)
    let context = UIGraphicsGetCurrentContext()
    context?.setStrokeColor(red: 1.0, green: 0.5, blue: 1.0, alpha: 1.0)
    context?.setLineWidth(5.0)
    context?.stroke(rect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage






    It will give you an image with pink border.






    share|improve this answer




















    • I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
      – Roman
      Dec 20 '17 at 7:16










    • Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
      – Arun Kumar
      Dec 20 '17 at 7:29










    • Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
      – Roman
      Dec 20 '17 at 7:59


















    0














    Here is a UIImage extension I wrote in Swift 4. As IOSDealBreaker said this is all about image processing, and some particular cases may occur. You should have a png image with a transparent background, and manage the size if larger than the original.



    • First get a colorised "shade" version of your image.

    • Then draw and redraw the shade image all around a given origin point (In our case around (0,0) at a distance that is the border thickness)

    • Draw your source image at the origin point so that it appears on the foreground.

    • You may have to enlarge your image if the borders go out of the original rect.

    My method uses a lot of util methods and class extensions. Here is some maths to rotate a vector (which is actually a point) around another point: Rotating a CGPoint around another CGPoint



    extension CGPoint 
    func rotated(around origin: CGPoint, byDegrees: CGFloat) -> CGPoint
    let dx = self.x - origin.x
    let dy = self.y - origin.y
    let radius = sqrt(dx * dx + dy * dy)
    let azimuth = atan2(dy, dx) // in radians
    let newAzimuth = azimuth + (byDegrees * CGFloat.pi / 180.0) // convert it to radians
    let x = origin.x + radius * cos(newAzimuth)
    let y = origin.y + radius * sin(newAzimuth)
    return CGPoint(x: x, y: y)




    I wrote my custom CIFilter to colorise an image which have a transparent background: Colorize a UIImage in Swift



    class ColorFilter: CIFilter 
    var inputImage: CIImage?
    var inputColor: CIColor?
    private let kernel: CIColorKernel =
    let kernelString =
    """
    kernel vec4 colorize(__sample pixel, vec4 color)
    pixel.rgb = pixel.a * color.rgb;
    pixel.a *= color.a;
    return pixel;

    """
    return CIColorKernel(source: kernelString)!
    ()

    override var outputImage: CIImage?
    guard let inputImage = inputImage, let inputColor = inputColor else return nil
    let inputs = [inputImage, inputColor] as [Any]
    return kernel.apply(extent: inputImage.extent, arguments: inputs)



    extension UIImage {
    func colorized(with color: UIColor) -> UIImage
    guard let cgInput = self.cgImage else
    return self

    let colorFilter = ColorFilter()
    colorFilter.inputImage = CIImage(cgImage: cgInput)
    colorFilter.inputColor = CIColor(color: color)

    if let ciOutputImage = colorFilter.outputImage
    let context = CIContext(options: nil)
    let cgImg = context.createCGImage(ciOutputImage, from: ciOutputImage.extent)
    return UIImage(cgImage: cgImg!, scale: self.scale, orientation: self.imageOrientation).alpha(color.rgba.alpha).withRenderingMode(self.renderingMode)
    else
    return self




    At this point you should have everything to make this work:



    extension UIImage 
    func stroked(with color: UIColor, size: CGFloat) -> UIImage
    let strokeImage = self.colorized(with: color)
    let oldRect = CGRect(x: size, y: size, width: self.size.width, height: self.size.height).integral
    let newSize = CGSize(width: self.size.width + (2*size), height: self.size.height + (2*size))
    let translationVector = CGPoint(x: size, y: 0)

    UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
    if let context = UIGraphicsGetCurrentContext()
    context.interpolationQuality = .high

    let step = 10 // reduce the step to increase quality
    for angle in stride(from: 0, to: 360, by: step)
    let vector = translationVector.rotated(around: .zero, byDegrees: CGFloat(angle))
    let transform = CGAffineTransform(translationX: vector.x, y: vector.y)
    context.concatenate(transform)
    context.draw(strokeImage.cgImage!, in: oldRect)
    let resetTransform = CGAffineTransform(translationX: -vector.x, y: -vector.y)
    context.concatenate(resetTransform)

    context.draw(self.cgImage!, in: oldRect)

    let newImage = UIImage(cgImage: context.makeImage()!, scale: self.scale, orientation: self.imageOrientation)
    UIGraphicsEndImageContext()

    return newImage.withRenderingMode(self.renderingMode)

    UIGraphicsEndImageContext()
    return self







    share|improve this answer






















      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47900243%2fhow-to-add-colored-border-to-uiimage-in-swift%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      3














      Here is the way how you can achieve that:



      Add below extension to your code:



      extension UIImage 
      func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
      let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
      let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
      imageView.contentMode = .center
      imageView.image = self
      imageView.layer.borderWidth = width
      imageView.layer.borderColor = color.cgColor
      UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
      guard let context = UIGraphicsGetCurrentContext() else return nil
      imageView.layer.render(in: context)
      let result = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return result




      And you can use it this way:



      let imgOriginal = UIImage.init(named: "Richie_Rich")
      img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)


      And result will be:



      enter image description here



      Here is the original post which is with Round corners but I removed that code because you did't ask for it.






      share|improve this answer




















      • I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
        – Roman
        Dec 20 '17 at 7:07











      • You already have it with above code. img.image is what you are looking for. @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:08











      • You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:17










      • Thank you Richie Rich, see my update with code above.
        – Roman
        Dec 20 '17 at 7:46















      3














      Here is the way how you can achieve that:



      Add below extension to your code:



      extension UIImage 
      func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
      let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
      let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
      imageView.contentMode = .center
      imageView.image = self
      imageView.layer.borderWidth = width
      imageView.layer.borderColor = color.cgColor
      UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
      guard let context = UIGraphicsGetCurrentContext() else return nil
      imageView.layer.render(in: context)
      let result = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return result




      And you can use it this way:



      let imgOriginal = UIImage.init(named: "Richie_Rich")
      img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)


      And result will be:



      enter image description here



      Here is the original post which is with Round corners but I removed that code because you did't ask for it.






      share|improve this answer




















      • I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
        – Roman
        Dec 20 '17 at 7:07











      • You already have it with above code. img.image is what you are looking for. @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:08











      • You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:17










      • Thank you Richie Rich, see my update with code above.
        – Roman
        Dec 20 '17 at 7:46













      3












      3








      3






      Here is the way how you can achieve that:



      Add below extension to your code:



      extension UIImage 
      func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
      let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
      let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
      imageView.contentMode = .center
      imageView.image = self
      imageView.layer.borderWidth = width
      imageView.layer.borderColor = color.cgColor
      UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
      guard let context = UIGraphicsGetCurrentContext() else return nil
      imageView.layer.render(in: context)
      let result = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return result




      And you can use it this way:



      let imgOriginal = UIImage.init(named: "Richie_Rich")
      img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)


      And result will be:



      enter image description here



      Here is the original post which is with Round corners but I removed that code because you did't ask for it.






      share|improve this answer












      Here is the way how you can achieve that:



      Add below extension to your code:



      extension UIImage 
      func imageWithBorder(width: CGFloat, color: UIColor) -> UIImage?
      let square = CGSize(width: min(size.width, size.height) + width * 2, height: min(size.width, size.height) + width * 2)
      let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: square))
      imageView.contentMode = .center
      imageView.image = self
      imageView.layer.borderWidth = width
      imageView.layer.borderColor = color.cgColor
      UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
      guard let context = UIGraphicsGetCurrentContext() else return nil
      imageView.layer.render(in: context)
      let result = UIGraphicsGetImageFromCurrentImageContext()
      UIGraphicsEndImageContext()
      return result




      And you can use it this way:



      let imgOriginal = UIImage.init(named: "Richie_Rich")
      img.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)


      And result will be:



      enter image description here



      Here is the original post which is with Round corners but I removed that code because you did't ask for it.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Dec 20 '17 at 6:56









      Dharmesh Kheni

      48.5k23121147




      48.5k23121147











      • I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
        – Roman
        Dec 20 '17 at 7:07











      • You already have it with above code. img.image is what you are looking for. @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:08











      • You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:17










      • Thank you Richie Rich, see my update with code above.
        – Roman
        Dec 20 '17 at 7:46
















      • I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
        – Roman
        Dec 20 '17 at 7:07











      • You already have it with above code. img.image is what you are looking for. @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:08











      • You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
        – Dharmesh Kheni
        Dec 20 '17 at 7:17










      • Thank you Richie Rich, see my update with code above.
        – Roman
        Dec 20 '17 at 7:46















      I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
      – Roman
      Dec 20 '17 at 7:07





      I tried to used you code and get border to the image view! But I need border to the image itself. let imgOriginal = UIImage.init(named: "plum") imageView.image = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue)
      – Roman
      Dec 20 '17 at 7:07













      You already have it with above code. img.image is what you are looking for. @Roman
      – Dharmesh Kheni
      Dec 20 '17 at 7:08





      You already have it with above code. img.image is what you are looking for. @Roman
      – Dharmesh Kheni
      Dec 20 '17 at 7:08













      You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
      – Dharmesh Kheni
      Dec 20 '17 at 7:17




      You can simple store it in variable like: let borderImage = imgOriginal?.imageWithBorder(width: 2, color: UIColor.blue) @Roman
      – Dharmesh Kheni
      Dec 20 '17 at 7:17












      Thank you Richie Rich, see my update with code above.
      – Roman
      Dec 20 '17 at 7:46




      Thank you Richie Rich, see my update with code above.
      – Roman
      Dec 20 '17 at 7:46













      0














      Borders to the images belongs to image processing area of iOS. It's not easy as borders for a UIView, It's pretty deep but if you're willing to go the distance, here is a library and a hint for the journey
      https://github.com/BradLarson/GPUImage



      try using GPUImageThresholdEdgeDetectionFilter



      or try OpenCV https://docs.opencv.org/2.4/doc/tutorials/ios/image_manipulation/image_manipulation.html






      share|improve this answer

























        0














        Borders to the images belongs to image processing area of iOS. It's not easy as borders for a UIView, It's pretty deep but if you're willing to go the distance, here is a library and a hint for the journey
        https://github.com/BradLarson/GPUImage



        try using GPUImageThresholdEdgeDetectionFilter



        or try OpenCV https://docs.opencv.org/2.4/doc/tutorials/ios/image_manipulation/image_manipulation.html






        share|improve this answer























          0












          0








          0






          Borders to the images belongs to image processing area of iOS. It's not easy as borders for a UIView, It's pretty deep but if you're willing to go the distance, here is a library and a hint for the journey
          https://github.com/BradLarson/GPUImage



          try using GPUImageThresholdEdgeDetectionFilter



          or try OpenCV https://docs.opencv.org/2.4/doc/tutorials/ios/image_manipulation/image_manipulation.html






          share|improve this answer












          Borders to the images belongs to image processing area of iOS. It's not easy as borders for a UIView, It's pretty deep but if you're willing to go the distance, here is a library and a hint for the journey
          https://github.com/BradLarson/GPUImage



          try using GPUImageThresholdEdgeDetectionFilter



          or try OpenCV https://docs.opencv.org/2.4/doc/tutorials/ios/image_manipulation/image_manipulation.html







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Dec 20 '17 at 6:50









          IOSDealBreaker

          697818




          697818





















              0














              Use this simple extension for UIImage



              extension UIImage 

              func outline() -> UIImage?

              UIGraphicsBeginImageContext(size)
              let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
              self.draw(in: rect, blendMode: .normal, alpha: 1.0)
              let context = UIGraphicsGetCurrentContext()
              context?.setStrokeColor(red: 1.0, green: 0.5, blue: 1.0, alpha: 1.0)
              context?.setLineWidth(5.0)
              context?.stroke(rect)
              let newImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()

              return newImage






              It will give you an image with pink border.






              share|improve this answer




















              • I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
                – Roman
                Dec 20 '17 at 7:16










              • Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
                – Arun Kumar
                Dec 20 '17 at 7:29










              • Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
                – Roman
                Dec 20 '17 at 7:59















              0














              Use this simple extension for UIImage



              extension UIImage 

              func outline() -> UIImage?

              UIGraphicsBeginImageContext(size)
              let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
              self.draw(in: rect, blendMode: .normal, alpha: 1.0)
              let context = UIGraphicsGetCurrentContext()
              context?.setStrokeColor(red: 1.0, green: 0.5, blue: 1.0, alpha: 1.0)
              context?.setLineWidth(5.0)
              context?.stroke(rect)
              let newImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()

              return newImage






              It will give you an image with pink border.






              share|improve this answer




















              • I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
                – Roman
                Dec 20 '17 at 7:16










              • Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
                – Arun Kumar
                Dec 20 '17 at 7:29










              • Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
                – Roman
                Dec 20 '17 at 7:59













              0












              0








              0






              Use this simple extension for UIImage



              extension UIImage 

              func outline() -> UIImage?

              UIGraphicsBeginImageContext(size)
              let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
              self.draw(in: rect, blendMode: .normal, alpha: 1.0)
              let context = UIGraphicsGetCurrentContext()
              context?.setStrokeColor(red: 1.0, green: 0.5, blue: 1.0, alpha: 1.0)
              context?.setLineWidth(5.0)
              context?.stroke(rect)
              let newImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()

              return newImage






              It will give you an image with pink border.






              share|improve this answer












              Use this simple extension for UIImage



              extension UIImage 

              func outline() -> UIImage?

              UIGraphicsBeginImageContext(size)
              let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
              self.draw(in: rect, blendMode: .normal, alpha: 1.0)
              let context = UIGraphicsGetCurrentContext()
              context?.setStrokeColor(red: 1.0, green: 0.5, blue: 1.0, alpha: 1.0)
              context?.setLineWidth(5.0)
              context?.stroke(rect)
              let newImage = UIGraphicsGetImageFromCurrentImageContext()
              UIGraphicsEndImageContext()

              return newImage






              It will give you an image with pink border.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Dec 20 '17 at 7:04









              Arun Kumar

              724415




              724415











              • I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
                – Roman
                Dec 20 '17 at 7:16










              • Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
                – Arun Kumar
                Dec 20 '17 at 7:29










              • Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
                – Roman
                Dec 20 '17 at 7:59
















              • I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
                – Roman
                Dec 20 '17 at 7:16










              • Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
                – Arun Kumar
                Dec 20 '17 at 7:29










              • Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
                – Roman
                Dec 20 '17 at 7:59















              I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
              – Roman
              Dec 20 '17 at 7:16




              I tried your code with: let image = UIImage(named: "plum")!.outline() and still get the border arounf the imge view and not around the image itself!
              – Roman
              Dec 20 '17 at 7:16












              Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
              – Arun Kumar
              Dec 20 '17 at 7:29




              Its around the image not the image view. Do one thing , Make your imageview bigger and keep its content mode property set to aspect fit and give it a background color. You will se the border around the image, not around the imageView.
              – Arun Kumar
              Dec 20 '17 at 7:29












              Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
              – Roman
              Dec 20 '17 at 7:59




              Hi Arun, I am trying to follow your suggestion but the result is not the right border. Could you give a short code for func perhaps, not only the extention?
              – Roman
              Dec 20 '17 at 7:59











              0














              Here is a UIImage extension I wrote in Swift 4. As IOSDealBreaker said this is all about image processing, and some particular cases may occur. You should have a png image with a transparent background, and manage the size if larger than the original.



              • First get a colorised "shade" version of your image.

              • Then draw and redraw the shade image all around a given origin point (In our case around (0,0) at a distance that is the border thickness)

              • Draw your source image at the origin point so that it appears on the foreground.

              • You may have to enlarge your image if the borders go out of the original rect.

              My method uses a lot of util methods and class extensions. Here is some maths to rotate a vector (which is actually a point) around another point: Rotating a CGPoint around another CGPoint



              extension CGPoint 
              func rotated(around origin: CGPoint, byDegrees: CGFloat) -> CGPoint
              let dx = self.x - origin.x
              let dy = self.y - origin.y
              let radius = sqrt(dx * dx + dy * dy)
              let azimuth = atan2(dy, dx) // in radians
              let newAzimuth = azimuth + (byDegrees * CGFloat.pi / 180.0) // convert it to radians
              let x = origin.x + radius * cos(newAzimuth)
              let y = origin.y + radius * sin(newAzimuth)
              return CGPoint(x: x, y: y)




              I wrote my custom CIFilter to colorise an image which have a transparent background: Colorize a UIImage in Swift



              class ColorFilter: CIFilter 
              var inputImage: CIImage?
              var inputColor: CIColor?
              private let kernel: CIColorKernel =
              let kernelString =
              """
              kernel vec4 colorize(__sample pixel, vec4 color)
              pixel.rgb = pixel.a * color.rgb;
              pixel.a *= color.a;
              return pixel;

              """
              return CIColorKernel(source: kernelString)!
              ()

              override var outputImage: CIImage?
              guard let inputImage = inputImage, let inputColor = inputColor else return nil
              let inputs = [inputImage, inputColor] as [Any]
              return kernel.apply(extent: inputImage.extent, arguments: inputs)



              extension UIImage {
              func colorized(with color: UIColor) -> UIImage
              guard let cgInput = self.cgImage else
              return self

              let colorFilter = ColorFilter()
              colorFilter.inputImage = CIImage(cgImage: cgInput)
              colorFilter.inputColor = CIColor(color: color)

              if let ciOutputImage = colorFilter.outputImage
              let context = CIContext(options: nil)
              let cgImg = context.createCGImage(ciOutputImage, from: ciOutputImage.extent)
              return UIImage(cgImage: cgImg!, scale: self.scale, orientation: self.imageOrientation).alpha(color.rgba.alpha).withRenderingMode(self.renderingMode)
              else
              return self




              At this point you should have everything to make this work:



              extension UIImage 
              func stroked(with color: UIColor, size: CGFloat) -> UIImage
              let strokeImage = self.colorized(with: color)
              let oldRect = CGRect(x: size, y: size, width: self.size.width, height: self.size.height).integral
              let newSize = CGSize(width: self.size.width + (2*size), height: self.size.height + (2*size))
              let translationVector = CGPoint(x: size, y: 0)

              UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
              if let context = UIGraphicsGetCurrentContext()
              context.interpolationQuality = .high

              let step = 10 // reduce the step to increase quality
              for angle in stride(from: 0, to: 360, by: step)
              let vector = translationVector.rotated(around: .zero, byDegrees: CGFloat(angle))
              let transform = CGAffineTransform(translationX: vector.x, y: vector.y)
              context.concatenate(transform)
              context.draw(strokeImage.cgImage!, in: oldRect)
              let resetTransform = CGAffineTransform(translationX: -vector.x, y: -vector.y)
              context.concatenate(resetTransform)

              context.draw(self.cgImage!, in: oldRect)

              let newImage = UIImage(cgImage: context.makeImage()!, scale: self.scale, orientation: self.imageOrientation)
              UIGraphicsEndImageContext()

              return newImage.withRenderingMode(self.renderingMode)

              UIGraphicsEndImageContext()
              return self







              share|improve this answer



























                0














                Here is a UIImage extension I wrote in Swift 4. As IOSDealBreaker said this is all about image processing, and some particular cases may occur. You should have a png image with a transparent background, and manage the size if larger than the original.



                • First get a colorised "shade" version of your image.

                • Then draw and redraw the shade image all around a given origin point (In our case around (0,0) at a distance that is the border thickness)

                • Draw your source image at the origin point so that it appears on the foreground.

                • You may have to enlarge your image if the borders go out of the original rect.

                My method uses a lot of util methods and class extensions. Here is some maths to rotate a vector (which is actually a point) around another point: Rotating a CGPoint around another CGPoint



                extension CGPoint 
                func rotated(around origin: CGPoint, byDegrees: CGFloat) -> CGPoint
                let dx = self.x - origin.x
                let dy = self.y - origin.y
                let radius = sqrt(dx * dx + dy * dy)
                let azimuth = atan2(dy, dx) // in radians
                let newAzimuth = azimuth + (byDegrees * CGFloat.pi / 180.0) // convert it to radians
                let x = origin.x + radius * cos(newAzimuth)
                let y = origin.y + radius * sin(newAzimuth)
                return CGPoint(x: x, y: y)




                I wrote my custom CIFilter to colorise an image which have a transparent background: Colorize a UIImage in Swift



                class ColorFilter: CIFilter 
                var inputImage: CIImage?
                var inputColor: CIColor?
                private let kernel: CIColorKernel =
                let kernelString =
                """
                kernel vec4 colorize(__sample pixel, vec4 color)
                pixel.rgb = pixel.a * color.rgb;
                pixel.a *= color.a;
                return pixel;

                """
                return CIColorKernel(source: kernelString)!
                ()

                override var outputImage: CIImage?
                guard let inputImage = inputImage, let inputColor = inputColor else return nil
                let inputs = [inputImage, inputColor] as [Any]
                return kernel.apply(extent: inputImage.extent, arguments: inputs)



                extension UIImage {
                func colorized(with color: UIColor) -> UIImage
                guard let cgInput = self.cgImage else
                return self

                let colorFilter = ColorFilter()
                colorFilter.inputImage = CIImage(cgImage: cgInput)
                colorFilter.inputColor = CIColor(color: color)

                if let ciOutputImage = colorFilter.outputImage
                let context = CIContext(options: nil)
                let cgImg = context.createCGImage(ciOutputImage, from: ciOutputImage.extent)
                return UIImage(cgImage: cgImg!, scale: self.scale, orientation: self.imageOrientation).alpha(color.rgba.alpha).withRenderingMode(self.renderingMode)
                else
                return self




                At this point you should have everything to make this work:



                extension UIImage 
                func stroked(with color: UIColor, size: CGFloat) -> UIImage
                let strokeImage = self.colorized(with: color)
                let oldRect = CGRect(x: size, y: size, width: self.size.width, height: self.size.height).integral
                let newSize = CGSize(width: self.size.width + (2*size), height: self.size.height + (2*size))
                let translationVector = CGPoint(x: size, y: 0)

                UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
                if let context = UIGraphicsGetCurrentContext()
                context.interpolationQuality = .high

                let step = 10 // reduce the step to increase quality
                for angle in stride(from: 0, to: 360, by: step)
                let vector = translationVector.rotated(around: .zero, byDegrees: CGFloat(angle))
                let transform = CGAffineTransform(translationX: vector.x, y: vector.y)
                context.concatenate(transform)
                context.draw(strokeImage.cgImage!, in: oldRect)
                let resetTransform = CGAffineTransform(translationX: -vector.x, y: -vector.y)
                context.concatenate(resetTransform)

                context.draw(self.cgImage!, in: oldRect)

                let newImage = UIImage(cgImage: context.makeImage()!, scale: self.scale, orientation: self.imageOrientation)
                UIGraphicsEndImageContext()

                return newImage.withRenderingMode(self.renderingMode)

                UIGraphicsEndImageContext()
                return self







                share|improve this answer

























                  0












                  0








                  0






                  Here is a UIImage extension I wrote in Swift 4. As IOSDealBreaker said this is all about image processing, and some particular cases may occur. You should have a png image with a transparent background, and manage the size if larger than the original.



                  • First get a colorised "shade" version of your image.

                  • Then draw and redraw the shade image all around a given origin point (In our case around (0,0) at a distance that is the border thickness)

                  • Draw your source image at the origin point so that it appears on the foreground.

                  • You may have to enlarge your image if the borders go out of the original rect.

                  My method uses a lot of util methods and class extensions. Here is some maths to rotate a vector (which is actually a point) around another point: Rotating a CGPoint around another CGPoint



                  extension CGPoint 
                  func rotated(around origin: CGPoint, byDegrees: CGFloat) -> CGPoint
                  let dx = self.x - origin.x
                  let dy = self.y - origin.y
                  let radius = sqrt(dx * dx + dy * dy)
                  let azimuth = atan2(dy, dx) // in radians
                  let newAzimuth = azimuth + (byDegrees * CGFloat.pi / 180.0) // convert it to radians
                  let x = origin.x + radius * cos(newAzimuth)
                  let y = origin.y + radius * sin(newAzimuth)
                  return CGPoint(x: x, y: y)




                  I wrote my custom CIFilter to colorise an image which have a transparent background: Colorize a UIImage in Swift



                  class ColorFilter: CIFilter 
                  var inputImage: CIImage?
                  var inputColor: CIColor?
                  private let kernel: CIColorKernel =
                  let kernelString =
                  """
                  kernel vec4 colorize(__sample pixel, vec4 color)
                  pixel.rgb = pixel.a * color.rgb;
                  pixel.a *= color.a;
                  return pixel;

                  """
                  return CIColorKernel(source: kernelString)!
                  ()

                  override var outputImage: CIImage?
                  guard let inputImage = inputImage, let inputColor = inputColor else return nil
                  let inputs = [inputImage, inputColor] as [Any]
                  return kernel.apply(extent: inputImage.extent, arguments: inputs)



                  extension UIImage {
                  func colorized(with color: UIColor) -> UIImage
                  guard let cgInput = self.cgImage else
                  return self

                  let colorFilter = ColorFilter()
                  colorFilter.inputImage = CIImage(cgImage: cgInput)
                  colorFilter.inputColor = CIColor(color: color)

                  if let ciOutputImage = colorFilter.outputImage
                  let context = CIContext(options: nil)
                  let cgImg = context.createCGImage(ciOutputImage, from: ciOutputImage.extent)
                  return UIImage(cgImage: cgImg!, scale: self.scale, orientation: self.imageOrientation).alpha(color.rgba.alpha).withRenderingMode(self.renderingMode)
                  else
                  return self




                  At this point you should have everything to make this work:



                  extension UIImage 
                  func stroked(with color: UIColor, size: CGFloat) -> UIImage
                  let strokeImage = self.colorized(with: color)
                  let oldRect = CGRect(x: size, y: size, width: self.size.width, height: self.size.height).integral
                  let newSize = CGSize(width: self.size.width + (2*size), height: self.size.height + (2*size))
                  let translationVector = CGPoint(x: size, y: 0)

                  UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
                  if let context = UIGraphicsGetCurrentContext()
                  context.interpolationQuality = .high

                  let step = 10 // reduce the step to increase quality
                  for angle in stride(from: 0, to: 360, by: step)
                  let vector = translationVector.rotated(around: .zero, byDegrees: CGFloat(angle))
                  let transform = CGAffineTransform(translationX: vector.x, y: vector.y)
                  context.concatenate(transform)
                  context.draw(strokeImage.cgImage!, in: oldRect)
                  let resetTransform = CGAffineTransform(translationX: -vector.x, y: -vector.y)
                  context.concatenate(resetTransform)

                  context.draw(self.cgImage!, in: oldRect)

                  let newImage = UIImage(cgImage: context.makeImage()!, scale: self.scale, orientation: self.imageOrientation)
                  UIGraphicsEndImageContext()

                  return newImage.withRenderingMode(self.renderingMode)

                  UIGraphicsEndImageContext()
                  return self







                  share|improve this answer














                  Here is a UIImage extension I wrote in Swift 4. As IOSDealBreaker said this is all about image processing, and some particular cases may occur. You should have a png image with a transparent background, and manage the size if larger than the original.



                  • First get a colorised "shade" version of your image.

                  • Then draw and redraw the shade image all around a given origin point (In our case around (0,0) at a distance that is the border thickness)

                  • Draw your source image at the origin point so that it appears on the foreground.

                  • You may have to enlarge your image if the borders go out of the original rect.

                  My method uses a lot of util methods and class extensions. Here is some maths to rotate a vector (which is actually a point) around another point: Rotating a CGPoint around another CGPoint



                  extension CGPoint 
                  func rotated(around origin: CGPoint, byDegrees: CGFloat) -> CGPoint
                  let dx = self.x - origin.x
                  let dy = self.y - origin.y
                  let radius = sqrt(dx * dx + dy * dy)
                  let azimuth = atan2(dy, dx) // in radians
                  let newAzimuth = azimuth + (byDegrees * CGFloat.pi / 180.0) // convert it to radians
                  let x = origin.x + radius * cos(newAzimuth)
                  let y = origin.y + radius * sin(newAzimuth)
                  return CGPoint(x: x, y: y)




                  I wrote my custom CIFilter to colorise an image which have a transparent background: Colorize a UIImage in Swift



                  class ColorFilter: CIFilter 
                  var inputImage: CIImage?
                  var inputColor: CIColor?
                  private let kernel: CIColorKernel =
                  let kernelString =
                  """
                  kernel vec4 colorize(__sample pixel, vec4 color)
                  pixel.rgb = pixel.a * color.rgb;
                  pixel.a *= color.a;
                  return pixel;

                  """
                  return CIColorKernel(source: kernelString)!
                  ()

                  override var outputImage: CIImage?
                  guard let inputImage = inputImage, let inputColor = inputColor else return nil
                  let inputs = [inputImage, inputColor] as [Any]
                  return kernel.apply(extent: inputImage.extent, arguments: inputs)



                  extension UIImage {
                  func colorized(with color: UIColor) -> UIImage
                  guard let cgInput = self.cgImage else
                  return self

                  let colorFilter = ColorFilter()
                  colorFilter.inputImage = CIImage(cgImage: cgInput)
                  colorFilter.inputColor = CIColor(color: color)

                  if let ciOutputImage = colorFilter.outputImage
                  let context = CIContext(options: nil)
                  let cgImg = context.createCGImage(ciOutputImage, from: ciOutputImage.extent)
                  return UIImage(cgImage: cgImg!, scale: self.scale, orientation: self.imageOrientation).alpha(color.rgba.alpha).withRenderingMode(self.renderingMode)
                  else
                  return self




                  At this point you should have everything to make this work:



                  extension UIImage 
                  func stroked(with color: UIColor, size: CGFloat) -> UIImage
                  let strokeImage = self.colorized(with: color)
                  let oldRect = CGRect(x: size, y: size, width: self.size.width, height: self.size.height).integral
                  let newSize = CGSize(width: self.size.width + (2*size), height: self.size.height + (2*size))
                  let translationVector = CGPoint(x: size, y: 0)

                  UIGraphicsBeginImageContextWithOptions(newSize, false, self.scale)
                  if let context = UIGraphicsGetCurrentContext()
                  context.interpolationQuality = .high

                  let step = 10 // reduce the step to increase quality
                  for angle in stride(from: 0, to: 360, by: step)
                  let vector = translationVector.rotated(around: .zero, byDegrees: CGFloat(angle))
                  let transform = CGAffineTransform(translationX: vector.x, y: vector.y)
                  context.concatenate(transform)
                  context.draw(strokeImage.cgImage!, in: oldRect)
                  let resetTransform = CGAffineTransform(translationX: -vector.x, y: -vector.y)
                  context.concatenate(resetTransform)

                  context.draw(self.cgImage!, in: oldRect)

                  let newImage = UIImage(cgImage: context.makeImage()!, scale: self.scale, orientation: self.imageOrientation)
                  UIGraphicsEndImageContext()

                  return newImage.withRenderingMode(self.renderingMode)

                  UIGraphicsEndImageContext()
                  return self








                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 13 at 9:23

























                  answered Nov 12 at 11:05









                  herme5

                  1088




                  1088



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47900243%2fhow-to-add-colored-border-to-uiimage-in-swift%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      27

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      Category:Rhetoric