2

A layer's borderWidth and borderColor properties draw a border inside the view. Remykits pointed this out here.

A layer's shadow... properties cannot be used to create a border that both appears on all four sides and is opaque for reasons I showed here.

What I failed to specify in that question (and the reason I've opened a new one) is that I want the border to be outside the view. Increasing the frame of the view to compensate for the space lost, as has been suggested, doesn't work; I'm using a UIImageView, so even if the frame is increased, the image is still cropped.

Another suggestion was to change the contentMode of the UIImageView to .Center, in combination with changing the size of the view, but this doesn't work as the view then isn't the proper size.

The solution I first thought of was to create another UIView "behind" this UIImageView, and give it a backgroundColor to mimic the effect of a border. I also thought of creating a custom subclass of UImageView. Both courses of action, however, involve making calculations based on the frame of the view. I've had many problems with the frame not being set by AutoLayout at the proper time, etc.

Other things that come to mind are digitally adding a border to the image or positioning the image in a specific part of the UIImageView. (My attempt at the latter was imageView.layer.contentsRect = CGRectInset(imageView.bounds, 4, 4), which resulted in a strangely pixellated image.)

To be clear, what I'm looking for is this: enter image description here

It really feels like there should be a simpler way to do this than creating a new class or view. Any help appreciated.

Community
  • 1
  • 1
Randoms
  • 2,110
  • 2
  • 20
  • 31
  • 1
    Did you try to change the `UIImage` size and put it into `UIImageView` which background color is changes as border color? Also set `contentMode` to center. This can be work if you are cropping the image with imageview. – AykutE Jan 08 '16 at 01:02

1 Answers1

0

Aha! Stitching together aykutt's comment about resizing the image and changing the conentMode, Paul Lynch's answer about resizing images, and rene's (life-saving) answer about what to do your subviews actually aren't laid out in viewDidLayoutSubviews:

override func viewDidLayoutSubviews() {

    super.viewDidLayoutSubviews()

    self.myContainer.setNeedsLayout()
    self.myContainer.layoutIfNeeded()

    var width: CGFloat = 4 //the same width used for the border of the imageView
    var rect = CGRectInset(imageView.bounds, width, width)
    var size = CGSizeMake(rect.width, rect.height)
    UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
    image.drawInRect(CGRectMake(0, 0, size.width, size.height))
    var new = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    self.imageView.contentMode = .Center
    self.imageView.image = new

}
Community
  • 1
  • 1
Randoms
  • 2,110
  • 2
  • 20
  • 31