I got a UITableView with default cell styles. (set to .subtitle style)
I want to make its UIImageView circular.
cell.imageView.layer.borderWidth = 1
cell.imageView.layer.masksToBounds = false
cell.imageView.layer.borderColor = UIColor.white.cgColor
cell.imageView.layer.cornerRadius = profileImageView.frame.size.width/2
cell.imageView.clipsToBounds = true
this would not work at this situation!
I found the right way thanks to https://stackoverflow.com/a/50462058/10489699 .
let itemSize = CGSize.init(width: 50, height: 50)
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale)
let imageRect = CGRect.init(origin: CGPoint.zero, size: itemSize)
cell.imageView?.image!.draw(in: imageRect)
cell.imageView?.image! = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
cell.imageView?.layer.cornerRadius = (itemSize.width) / 2
cell.imageView?.clipsToBounds = true
Don't try if let image = cell.imageView?.image! {...} , I don't know why but it hits the UIImageView !
you can use this code
public extension UIView {
func round() {
let width = bounds.width < bounds.height ? bounds.width : bounds.height
let mask = CAShapeLayer()
mask.path = UIBezierPath(ovalIn: CGRect(x: bounds.midX - width / 2, y: bounds.midY - width / 2, width: width, height: width)).cgPath
self.layer.mask = mask
}
}
and you can use like this:
profileImageView.round()
Related
Here is what I am trying to do:
The screenshot is taken from Iphone:
This is my code:
cell.shadowLayerView.layer.masksToBounds = false
cell.shadowLayerView.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.shadowLayerView.layer.shadowColor = UIColor.black.cgColor
cell.shadowLayerView.layer.shadowOpacity = 0.23
cell.shadowLayerView.layer.shadowRadius = 4
cell.shadowLayerView.layer.shadowPath = UIBezierPath(roundedRect: cell.shadowLayerView.bounds, cornerRadius: 2).cgPath
cell.shadowLayerView.layer.shouldRasterize = true
cell.shadowLayerView.layer.rasterizationScale = UIScreen.main.scale
cell.discriptionLbl.frame.size.width = UIScreen.main.bounds.size.width
This is my tableview xib. In original image show light gray color shadow all side(Top,Bottom,left,Right) but in taken image show all side shadow but why show extra shadow in right side and bottom side.
See Below Image:
Question: How to show same shadow from all side of the view like original image(shadow in light gray color)?
Can someone please explain to me how to solve this , i've tried to solve this issue but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
See the below code:
mainViewCorner.layer.shadowColor = UIColor.red.cgColor;
mainViewCorner.layer.shadowOffset = CGSize.zero //direction of shadow
mainViewCorner.layer.shadowOpacity = 1.0; // opacity for shadow
mainViewCorner.layer.shadowRadius = 0.0; //amount of shadow to blur
mainViewCorner.layer.cornerRadius = 4.0;
issue with your code was shadowOffset. It defines the direction of your shadow. If you want shadow on all sides - it must have zero value for both width and height.
try it
myView.layer.cornerRadius = 10
let shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 10)
myView.layer.masksToBounds = false
myView.layer.shadowColor = UIColor.gray.cgColor
myView.layer.shadowOffset = CGSize(width: 0, height: 2)
myView.layer.shadowOpacity = 0.5
Or you can use Sketch Shadow
extension CALayer {
func applySketchShadow(
color: UIColor = .black,
alpha: Float = 0.5,
x: CGFloat = 0,
y: CGFloat = 2,
blur: CGFloat = 4,
spread: CGFloat = 0)
{
shadowColor = color.cgColor
shadowOpacity = alpha
shadowOffset = CGSize(width: x, height: y)
shadowRadius = blur / 2.0
if spread == 0 {
shadowPath = nil
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(rect: rect).cgPath
}
}
}
apply Sketch Shadow
myView.layer.cornerRadius = 10
let shadowPath = UIBezierPath(roundedRect: myView.bounds, cornerRadius: 10)
myView.layer.applySketchShadow(
color: .black,
alpha: 0.5,
x: CGFloat(0),
y: CGFloat(10),
blur: 20,
spread: 0)
myView.layer.shadowPath = shadowPath.cgPath
How can I add padding between an UIImageView and its border?
Img.layer.cornerRadius = Img.bounds.width / 2
Img.layer.borderWidth = 2
Img.layer.borderColor = UIColor.blue.cgColor
Img.clipsToBounds = true
Like this:
As per the this link
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "imagename")!
let imageView = UIImageView(image: image.imageWithInsets(insets: UIEdgeInsetsMake(30, 30, 30, 30)))
imageView.frame = CGRect(x: 0, y: 0, width: 300, height: 400)
imageView.backgroundColor = UIColor.gray
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.blue.cgColor
view.addSubview(imageView)
}
}
extension UIImage {
func imageWithInsets(insets: UIEdgeInsets) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(
CGSize(width: self.size.width + insets.left + insets.right,
height: self.size.height + insets.top + insets.bottom), false, self.scale)
let _ = UIGraphicsGetCurrentContext()
let origin = CGPoint(x: insets.left, y: insets.top)
self.draw(at: origin)
let imageWithInsets = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageWithInsets
}
}
For adding padding to the UIImage of UIImageView, use the below piece of code in Swift
let padding: CGFloat = 6
myImageView.contentMode = .scaleAspectFill
myImageView.image = UIImage(named: "myImage.png").resizableImage(withCapInsets: UIEdgeInsets(top: padding, left: padding, bottom: padding, right: padding), resizingMode: .stretch)
I have been looking at many stack overflow posts but none have them have been able to give me my desired solution. So far I have been able to get an image and convert it into a circle using AlamoFire. However, unfortunately alamo fire does not provide an option to add a border to a UIImage. I was wondering if anyone had a solution to my problem. Here is my code for making the image into a circle:
if let downloadedImage = UIImage(data: data!) {
let markerImage = downloadedImage
let markerImageSize = CGSize(width: 50, height: 50)
let markerImageFilter = AspectScaledToFillSizeCircleFilter(size: markerImageSize)
let finalMarkerImage = markerImageFilter.filter(markerImage)
marker.icon = finalMarkerImage
}
As you can see I am able to get a circle but not one with a border. So far I have tried many stack overflow post solutions to try and work with my AlamoFire solution. Here are some of the posts:
Making a UIImage to a circle form
Cut a UIImage into a circle Swift(iOS)
Here is what I currently have:
Here is what I want:
Any help would be much appreciated. Thanks!
I would suggest that you should apply the required appearance to the UIImageView that contains your UIImage, as follows:
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.brown.cgColor
Update:
Since you are working with Google Maps (GMSMarker), you should create an UIImageView programmatically (apply the above code snippet to it) and add it to your marker as iconView, as follows:
marker.iconView = imageView
So, it should be similar to:
// of course the values of the width/height (size) is up to you
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
imageView.layer.cornerRadius = imageView.frame.size.width / 2
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 2
imageView.layer.borderColor = UIColor.white.cgColor
// set your image
imageView.image = ...
marker.iconView = imageView
This should create round image with white border…
func round(image: UIImage) -> UIImage {
let imageWidth = image.size.width
let imageHeight = image.size.height
let diameter = min(imageWidth, imageHeight)
let isLandscape = imageWidth > imageHeight
let xOffset = isLandscape ? (imageWidth - diameter) / 2 : 0
let yOffset = isLandscape ? 0 : (imageHeight - diameter) / 2
let imageSize = CGSize(width: diameter, height: diameter)
return UIGraphicsImageRenderer(size: imageSize).image { _ in
let ovalPath = UIBezierPath(ovalIn: CGRect(origin: .zero, size: imageSize))
ovalPath.addClip()
image.draw(at: CGPoint(x: -xOffset, y: -yOffset))
UIColor.white.setStroke()
ovalPath.lineWidth = diameter / 50
ovalPath.stroke()
}
}
Then
let roundImage = round(image: downloadedImage)
for people struggling with the obj-c version of #ashley answer. Same logic
+ (UIImage *)drawBorderToImage:(UIImage *)image withColor:(UIColor *)color andThickness:(CGFloat)thickness {
CGFloat diameter = MIN(image.size.width, image.size.height);
BOOL isLandscape = image.size.width > image.size.height;
CGFloat xOffset = isLandscape ? (image.size.width - diameter) / 2 : 0;
CGFloat yOffset = isLandscape ? 0 : (image.size.height - diameter) / 2;
CGSize imageSize = CGSizeMake(diameter, diameter);
UIGraphicsBeginImageContext(image.size);
UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, imageSize.width, imageSize.height)];
[ovalPath addClip];
[image drawAtPoint:CGPointMake(-xOffset, -yOffset)];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, color.CGColor);
ovalPath.lineWidth = thickness;
[ovalPath stroke];
UIImage *borderedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return borderedImage;
}
I have a UITextField that must have a bottom border. Since autolayout use my code is this:
override func viewDidLayoutSubviews() {
let border = CALayer()
let width = CGFloat(0.5)
border.borderColor = UIColor.darkGray.withAlphaComponent(0.3).cgColor
border.frame = CGRect(x: 0, y: txtUsername.frame.size.height - width, width: txtUsername.frame.size.width, height: txtUsername.frame.size.height)
border.borderWidth = width
txtUsername.layer.addSublayer(border)
txtUsername.layer.masksToBounds = true
}
This, however, excludes the fact that when I touch the UITextField, this should create me a shadow. the code is this:
//ombra txtField
self.view.addSubview(txtUsername)
txtUsername.layer.shadowOffset = CGSize(width: 5, height: 10)
txtUsername.layer.shadowOpacity = 0.3
txtUsername.layer.shadowRadius = 10
txtUsername.layer.masksToBounds = false;
txtUsername.clipsToBounds = false
the one excludes the other. how do I fix?`
You can use CAShapeLayerShadow
func border(){
let border = CALayer()
let width = CGFloat(0.5)
border.borderColor = UIColor.darkGray.withAlphaComponent(1).cgColor
border.frame = CGRect(x: 0, y: CustomerTextBox.frame.size.height - width, width: CustomerTextBox.frame.size.width, height: CustomerTextBox.frame.size.height)
border.borderWidth = width
CustomerTextBox.layer.addSublayer(border)
CustomerTextBox.layer.masksToBounds = true
}
func shadow(){
let Shape = CAShapeLayer()
let myPath = UIBezierPath(ovalIn: CustomerTextBox.frame)
Shape.shadowPath = myPath.cgPath
Shape.shadowColor = UIColor.lightGray.cgColor
Shape.shadowOffset = CGSize(width: 5, height: 3)
Shape.shadowRadius = 5
Shape.shadowOpacity = 0.8
view.layer.insertSublayer(Shape, at: 0)
}
so I want to show some pictures as annotations on the map. In order to do that I need to add the image property of the MKAnnotationView. I'm using the regular images but I want them to be rounded and with a border. So I found a way to round UIImage and I found the way to add a border to UIImage, but border doesn't seem to add (I'm not actually having the image on the screen, maybe that is the problem?).
I used this answer https://stackoverflow.com/a/29047372/4665643 with a slight modification for border. Namely:
imageView.layer.borderWidth = 1.5
imageView.layer.borderColor = UIColor.whiteColor().CGColor
imageView.clipsToBounds = true
But my image on the map doesn't have any border. Any suggestions ?
imageView.layer.masksToBounds = true
imageView.layer.borderWidth = 1.5
imageView.layer.borderColor = UIColor.white.cgColor
imageView.layer.cornerRadius = imageView.bounds.width / 2
Try this.
If you would like to add a border to your image you need to make sure you add some extra room to it otherwise your border will be placed in top of your image. The solution is to add twice the width of your stroke to your image's width and height.
extension UIImage {
var isPortrait: Bool { size.height > size.width }
var isLandscape: Bool { size.width > size.height }
var breadth: CGFloat { min(size.width, size.height) }
var breadthSize: CGSize { .init(width: breadth, height: breadth) }
var breadthRect: CGRect { .init(origin: .zero, size: breadthSize) }
func rounded(with color: UIColor, width: CGFloat) -> UIImage? {
let bleed = breadthRect.insetBy(dx: -width, dy: -width)
UIGraphicsBeginImageContextWithOptions(bleed.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let cgImage = cgImage?.cropping(to: CGRect(origin: CGPoint(
x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
y: isPortrait ? ((size.height-size.width)/2).rounded(.down) : 0),
size: breadthSize))
else { return nil }
UIBezierPath(ovalIn: .init(origin: .zero, size: bleed.size)).addClip()
var strokeRect = breadthRect.insetBy(dx: -width/2, dy: -width/2)
strokeRect.origin = .init(x: width/2, y: width/2)
UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
.draw(in: strokeRect.insetBy(dx: width/2, dy: width/2))
color.set()
let line: UIBezierPath = .init(ovalIn: strokeRect)
line.lineWidth = width
line.stroke()
return UIGraphicsGetImageFromCurrentImageContext()
}
}
For iOS10+ We can use UIGraphicsImageRenderer.
extension UIImage {
var isPortrait: Bool { size.height > size.width }
var isLandscape: Bool { size.width > size.height }
var breadth: CGFloat { min(size.width, size.height) }
var breadthSize: CGSize { .init(width: breadth, height: breadth) }
var breadthRect: CGRect { .init(origin: .zero, size: breadthSize) }
func rounded(with color: UIColor, width: CGFloat) -> UIImage? {
guard let cgImage = cgImage?.cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : .zero, y: isPortrait ? ((size.height-size.width)/2).rounded(.down) : .zero), size: breadthSize)) else { return nil }
let bleed = breadthRect.insetBy(dx: -width, dy: -width)
let format = imageRendererFormat
format.opaque = false
return UIGraphicsImageRenderer(size: bleed.size, format: format).image { context in
UIBezierPath(ovalIn: .init(origin: .zero, size: bleed.size)).addClip()
var strokeRect = breadthRect.insetBy(dx: -width/2, dy: -width/2)
strokeRect.origin = .init(x: width/2, y: width/2)
UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
.draw(in: strokeRect.insetBy(dx: width/2, dy: width/2))
context.cgContext.setStrokeColor(color.cgColor)
let line: UIBezierPath = .init(ovalIn: strokeRect)
line.lineWidth = width
line.stroke()
}
}
}
Playground Testing:
let profilePicture = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
let pp = profilePicture.rounded(with: .red, width: 10)
Leo Dabus's solution in Swift 3:
extension UIImage {
func roundedImageWithBorder(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.cornerRadius = square.width/2
imageView.layer.masksToBounds = true
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
}
}
Use this extension to UIImageView :
func cropAsCircleWithBorder(borderColor : UIColor, strokeWidth: CGFloat)
{
var radius = min(self.bounds.width, self.bounds.height)
var drawingRect : CGRect = self.bounds
drawingRect.size.width = radius
drawingRect.origin.x = (self.bounds.size.width - radius) / 2
drawingRect.size.height = radius
drawingRect.origin.y = (self.bounds.size.height - radius) / 2
radius /= 2
var path = UIBezierPath(roundedRect: CGRectInset(drawingRect, strokeWidth/2, strokeWidth/2), cornerRadius: radius)
let border = CAShapeLayer()
border.fillColor = UIColor.clearColor().CGColor
border.path = path.CGPath
border.strokeColor = borderColor.CGColor
border.lineWidth = strokeWidth
self.layer.addSublayer(border)
path = UIBezierPath(roundedRect: drawingRect, cornerRadius: radius)
let mask = CAShapeLayer()
mask.path = path.CGPath
self.layer.mask = mask
}
Usage :
self.circleView.cropAsCircleWithBorder(UIColor.redColor(), strokeWidth: 20)
Result :
For making an image rounded with border, you can do that from User Defined Runtime Attributes also, no need to write code for that.
Please check the below image for setting that
Also in your code, change
imageView.layer.clipsToBounds = true
to this,
imageView.layer.masksToBounds = true
I set masksToBounds, and It work.
layer.masksToBounds = true
simple one line code its works for me
self.profileImage.layer.cornerRadius = self.profileImage.frame.size.width / 2
you can create an IBDesignable class and set it to your Image. Then change properties in Storyboard with realtime changes
#IBDesignable class CircularImageView: UIImageView {
#IBInspectable var borderWidth : CGFloat {
get { layer.borderWidth }
set {
layer.masksToBounds = true
layer.borderWidth = newValue
layer.cornerRadius = frame.size.width / 2
}
}
#IBInspectable var borderColor: UIColor? {
set {
guard let uiColor = newValue else { return }
layer.borderColor = uiColor.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
Just fixed it. Apparently everything was working perfectly but I wasn't seeing the border. The original image is about 300x300 pixels and with 1.5 pixel border I was cropping it to fit 40x40 frame so the border was barely noticeable. Changing border width to a bigger number made it visible.