Circular UIView (with cornerRadius) without Blended Layer - ios

I'm trying to get the circle below to have an opaque solid white color where the cornerRadius cuts out the UIView.
UIView *circle = [[UIView alloc] initWithFrame:CGRectMake(i * (todaySize + rightMargin), 0, smallSize, smallSize)];
circle.layer.cornerRadius = smallSize/2;
circle.layer.borderWidth = 0.5;
circle.layer.backgroundColor = [UIColor whiteColor].CGColor;
circle.backgroundColor = [UIColor whiteColor];
[self addSubview:circle];
I've tried a few things like setting the backgroundColor and opaque without any luck. Color Blended Layers still shows that the surrounding of the circle is transparent. Does anybody know how to solve this?

To avoid blending when using rounded corners, the rounding needs to be done in drawRect, rather than as a property on the layer. I needed UICollectionView cells with a rounded background in an app I'm working on. When I used layer.cornerRadius, the performance took a huge hit. Turning on color blended layers yielded the following:
Not what I was hoping for, I want those cells to be colored green indicating there is no blending occurring. To do this, I subclassed UIView into RoundedCornerView. My implementation is real short and sweet:
import UIKit
class RoundedCornerView: UIView {
static let cornerRadius = 40.0 as CGFloat
override func drawRect(rect: CGRect) {
let borderPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: RoundedCornerView.cornerRadius)
UIColor.whiteColor().set()
borderPath.fill()
}
}
Then I set the view I was rounding to be a RoundedCornerView in my nib. Running at that point yielded this:
Scrolling is buttery smooth and there is no longer any blending occurring. One odd side effect of this is that the view's backgroundColor property will color the excluded area of the corners, not the main body of the view. This means that the backgroundColor should be set to whatever is behind your view, not to the desired fill color.

Try using a mask to both avoid blending and dealing with the parent / child background color match.
override func layoutSubviews() {
super.layoutSubviews()
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 20).cgPath
layer.mask = maskLayer
}

Set clipsToBoundson the view or masksToBounds on the layer to YES

Related

What's currently the "correct" way to set a UIView's corner radius?

Setting a UIView's corner radius can be done the following ways:
Set the layer's cornerRadius property:
view.layer.cornerRadius = 5;
view.layer.masksToBounds = true;
Apply a mask:
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
Override draw(_:):
func draw(_ rect: CGRect) {
// Size of rounded rectangle
let rectWidth = rect.width
let rectHeight = rect.height
// Find center of actual frame to set rectangle in middle
let xf: CGFloat = (self.frame.width - rectWidth) / 2
let yf: CGFloat = (self.frame.height - rectHeight) / 2
let ctx = UIGraphicsGetCurrentContext()!
ctx.saveGState()
let rect = CGRect(x: xf, y: yf, width: rectWidth, height: rectHeight)
let clipPath = UIBezierPath(roundedRect: rect, cornerRadius: rectCornerRadius).cgPath
ctx.addPath(clipPath)
ctx.setFillColor(rectBgColor.cgColor)
ctx.closePath()
ctx.fillPath()
ctx.restoreGState()
}
Which of these is generally considered to be the "correct" way of implementing rounded corners on a UIView, accounting for the following criteria:
configuration (some corners may be rounded while others are not)
animation (can you animate the cornerRadius changing)
flexibility (does it break third party libraries or masks you have already applied)
readability (how concise/reusable is the solution)
speed (does it negatively impact performance)
Note that I don't know what's currently the “correct” way to set a UIView's corner radius.
What I prefer to do is to use Interface Builder as much as possible without having extra code which this approach shows and is reliable to my experience.
From iOS 11 upwards
you can use user-defined runtime attributes in the Identity inspector of the Interface Builder by setting the following properties:
layer.cornerRadius
layer.maskedCorners
layer.masksToBounds
According to the documentation of the CACornerMask you can see that the maskedCorners property is in fact a NSUInteger data type and you're allowed to set the following values:
kCALayerMinXMinYCorner = 1U << 0
kCALayerMaxXMinYCorner = 1U << 1
kCALayerMinXMaxYCorner = 1U << 2
kCALayerMaxXMaxYCorner = 1U << 3
Since you're allowed to bitwise OR those masks together you only have to "calculate" the resulting integer of that bitwise OR of what you actually need.
Therefore set the following number (integer) values for the maskedCorners property to get rounded corners:
0 = no corner is being rounded
1 = top left corner rounded only
2 = top right corner rounded only
3 = top left and top right corners rounded only
4 = bottom left corner rounded only
5 = top left and bottom left corners rounded only
6 = top right and bottom left corners rounded only
7 = top left, top right and bottom left corners rounded only
8 = bottom right corner rounded only
9 = top left and bottom right corners rounded only
10 = top right and bottom right corners rounded only
11 = top left, top right and bottom right corners rounded only
12 = bottom left and bottom right corners rounded only
13 = top left, bottom left and bottom right corners rounded only
14 = top right, bottom left and bottom right corners rounded only
15 = all corners rounded
Example: If you want to set the corner radius for the top-left and the top-right corners of a UIView you would use those attributes:
Re your three options:
Using CALayer existing properties: This is an easy (and likely the most efficient) solution for simple corner masking. It is animatable, too. In iOS 11 and later, you can pick which corners are to be masked.
Re custom CAShapeLayer masks: This is nice approach if the corner masking is not simple corner rounding but some arbitrary path. You have to be cautious to make sure to update this mask if the frame changes (e.g. update the path in layoutSubviews of view or in viewDidLayoutSubviews of controller).
Admittedly, if you want to do a very graceful animation as the view’s frame changes, that takes a little more work. But, as I point out above, simply responding to frame changes in layoutSubviews or viewDidLayoutSubviews is quite simple and takes care of it if you are not too worried about the corner rounding mid-animation.
Re custom draw(_:): This is more work than it is worth and you are probably not enjoying optimizations that Apple’s team may have done behind the scenes (e.g. what if subsequent draw calls are only drawing a portion of the full bounds; your code is redrawing the whole thing regardless).
I would suggest option 1 for simple cases, and option 2 if you need more control than option 1 can offer. But there is no “best” approach: It depends upon what you need and how much work you are willing to go through.
I did a couple of test with iOS 11 or lower version and the best practice I discovered for me to round a specific or all corners, you can do with the next code.
// Full size
CGSize vSize = [UIScreen mainScreen].bounds.size;
// Object
UIView *viewTest = [[UIView alloc] initWithFrame: CGRectMake(0, 0, vSize.width, vSize.height)];
[viewTest setAutoresizingMask: UIViewAutoresizingFlexibleHeight];
[viewTest setBackgroundColor: [UIColor grayColor]];
// maskedCorners is only available in iOS 11
if (#available(iOS 11.0, *)) {
[viewTest setClipsToBounds: YES];
[viewTest.layer setCornerRadius: 10];
// Only if you want to round the left and right top corners
[viewTest.layer setMaskedCorners: kCALayerMinXMinYCorner | kCALayerMaxXMinYCorner];
}
else {
// The old way used in lower version
CAShapeLayer *shapeLayerObj = [CAShapeLayer layer];
[shapeLayerObj setPath: [UIBezierPath bezierPathWithRoundedRect: viewTest.bounds byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){10.0, 10.}].CGPath];
[viewTest.layer setMask: shapeLayerObj];
}
This code fix the problem with autoResizingMask doesn't work when it use the old way to round corners.
Fix a bug with UIScrollView with round corners and setContentSize major to height of object.
The swift version it's something like this
let view = UIView()
view.clipsToBounds = true
view.layer.cornerRadius = 8
view.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner]
I think this is the most comprehensive summary of all: http://texturegroup.org/docs/corner-rounding.html
My heuristic is that if the view doesn't need a high performance (e.g. it's not inside a table view cell), the easiest option is using CALayer's cornerRadius. If you need some more advanced corner radius or high performance, then it's better to explore other options.
I go with the first one, it is the cleaner way of doing and you can do it in the IDE without code. Open the attributes inspector and then click on the Identity inspector and add under "User Defined Runtime attributes" those 2 properties:
contView.layer.cornerRadius = 25
contView.layer.maskedCorners = [.layerMaxXMinYCorner,.layerMinXMinYCorner]
contView.layer.masksToBounds = true
this is the result just top left and top right corners

Corners of button not staying rounded when using constraints constraints

I have two buttons in a stack view. I have used an extension of UIButton to round the outside corners. This works on the 7Plus which I designed for in storyboard but as soon as I run on a smaller device size in the simulator it stops working and I can only round corners on the left side of either button and not the right. Any ideas?
On a 7Plus
On a 7
These are the extensions I'm using
extension CGSize{
init(_ width:CGFloat,_ height:CGFloat) {
self.init(width:width,height:height)
}
}
extension UIButton{
func roundOneSide(topCorner: UIRectCorner, bottomCorner: UIRectCorner){
let maskPAth1 = UIBezierPath(roundedRect: self.bounds,
byRoundingCorners: [topCorner , bottomCorner],
cornerRadii:CGSize(6.0, 6.0))
let maskLayer1 = CAShapeLayer()
maskLayer1.frame = self.bounds
maskLayer1.path = maskPAth1.cgPath
self.layer.mask = maskLayer1
}
}
I have also tried the following code to no avail. It can only successfully round corners on the left when constraints come into play.
let maskLayer = CAShapeLayer()
maskLayer.path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: [.topLeft, .bottomRight], cornerRadii: CGSize(width: 6, height: 6)).cgPath
facebookBtn.layer.mask = maskLayer
facebookBtn.layer.masksToBounds = true
Use you use segment Control as jerky said or
Try this below code:
// For login button
UIBezierPath *cornersPathLeft = [UIBezierPath bezierPathWithRoundedRect:buttonLogin.bounds byRoundingCorners:(UIRectCornerBottomLeft|
UIRectCornerTopLeft) cornerRadii:CGSizeMake(5, 5)];
//Create a new layer to use as a mask
CAShapeLayer *maskLayerLeft = [CAShapeLayer layer];
// Set the path of the layer
maskLayerLeft.path = cornersPathLeft.CGPath;
buttonLogin.layer.mask = maskLayerLeft;
// For FB button
UIBezierPath *cornersPathRight = [UIBezierPath bezierPathWithRoundedRect:buttonFB.bounds byRoundingCorners:(UIRectCornerTopRight|
UIRectCornerBottomRight) cornerRadii:CGSizeMake(5, 5)];
CAShapeLayer *maskLayerRight = [CAShapeLayer layer];
maskLayerRight.path = cornersPathRight.CGPath;
buttonFB.layer.mask = maskLayerRight;
NOTE:
do maskToBounds = true it allows to give effect on the layers.
-
Difference Between MaskToBounds and ClipsToBounds
MaskToBounds
Any sublayers of the layer that extend outside its boundaries will be clipped to those boundaries. Think of the layer, in that case, as a window onto its sublayers; anything outside the edges of the window will not be visible. When masksToBounds = NO, no clipping occurs.
When the value of this property is true, Core Animation creates an implicit clipping mask that matches the bounds of the layer and includes any corner radius effects. If a value for the mask property is also specified, the two masks are multiplied to get the final mask value.
ClipsToBounds
The use case for clipsToBounds is more for subviews which are partially outside the main view.
For example, I have a (circular) subview on the edge of its parent (rectangular) UIView. If you set clipsToBounds to YES, only half the circle/subview will be shown. If set to NO, the whole circle will show up. Just encountered this so wanted to share
Conclusion
MaskToBounds are applied for the sublayer of any view. Like here OP added layer over button but it does not give effects. I mean layer is not bounds properly.
ClipToBounds are applied on the subVies of any view. Assume you have you have a view( says, viewBG ) and and now you added another view (says, upperView), now you dont wanted to see view upper to look outside the viewBG. ViewUpper always bounded inside its superview. so in this case you have to true the clipstobounds.
Practical experience
Try this below code in swift
let viewBG : UIView = UIView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
viewBG.backgroundColor = UIColor.lightGray
self.view.addSubview(viewBG)
let viewUpper : UIView = UIView(frame: CGRect(x: -50, y: -50, width: 100, height: 100))
viewUpper.backgroundColor = UIColor.blue
viewBG.addSubview(viewUpper)
Output
1. When i done viewBG.clipsToBounds = false
When i done viewBG.clipsToBounds = true
You need to enable clipToBound property of button in storyboard;
You could try a different, very simple method of curving the corners on a UIButton or Label.
Click on button
Click on identity inspector
Then add an attribute in the identity section
Key path is layer.cornerRadius
Set as Number
Finally give a value, the higher the value, the more rounded the corners are.
Well that was an easy fix. I just needed to round the corners in viewWillLayoutSubviews.
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
loginBtn.roundOneSide(topCorner: .topLeft, bottomCorner: .bottomLeft)
facebookBtn.roundOneSide(topCorner: .topRight, bottomCorner: .bottomRight)
}

Alpha gradient on view ios [duplicate]

Given an arbitrary UIView on iOS, is there a way using Core Graphics (CAGradientLayer comes to mind) to apply a "foreground-transparent" gradient to it?
I can't use a standard CAGradientLayer because the background is more complex than a UIColor. I also can't overlay a PNG because the background will change as my subview is scrolled along its parent vertical scrollview (see image).
I have a non-elegant fallback: have my uiview clip its subviews and move a pre-rendered gradient png of the background as the parent scrollview is scrolled.
This was an embarrassingly easy fix: apply a CAGradientLayer as my subview's mask.
CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = _fileTypeScrollView.bounds;
gradientLayer.colors = [NSArray arrayWithObjects:(id)[UIColor whiteColor].CGColor, (id)[UIColor clearColor].CGColor, nil];
gradientLayer.startPoint = CGPointMake(0.8f, 1.0f);
gradientLayer.endPoint = CGPointMake(1.0f, 1.0f);
_fileTypeScrollView.layer.mask = gradientLayer;
Thanks to Cocoanetics for pointing me in the right direction!
This is how I'll do.
Step 1 Define a custom gradient view (Swift 4):
import UIKit
class GradientView: UIView {
override open class var layerClass: AnyClass {
return CAGradientLayer.classForCoder()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let gradientLayer = self.layer as! CAGradientLayer
gradientLayer.colors = [
UIColor.white.cgColor,
UIColor.init(white: 1, alpha: 0).cgColor
]
backgroundColor = UIColor.clear
}
}
Step 2 - Drag and drop a UIView in your storyboard and set its custom class to GradientView
As an example, this is how the above gradient view looks like:
https://github.com/yzhong52/GradientViewDemo
I used the accepted (OP's) answer above and ran into the same issue noted in an upvoted comment - when the view scrolls, everything that started offscreen is now transparent, covered by the mask.
The solution was to add the gradient layer as the superview's mask, not the scroll view's mask. In my case, I'm using a text view, which is contained inside a view called contentView.
I added a third color and used locations instead of startPoint and endPoint, so that items below the text view are still visible.
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.contentView!.bounds
gradientLayer.colors = [UIColor.white.cgColor, UIColor.clear.cgColor, UIColor.white.cgColor]
// choose position for gradient, aligned to bottom of text view
let bottomOffset = (self.textView!.frame.size.height + self.textView!.frame.origin.y + 5)/self.contentView!.bounds.size.height
let topOffset = bottomOffset - 0.1
let bottomCoordinate = NSNumber(value: Double(bottomOffset))
let topCoordinate = NSNumber(value: Double(topOffset))
gradientLayer.locations = [topCoordinate, bottomCoordinate, bottomCoordinate]
self.contentView!.layer.mask = gradientLayer
Before, the text that started offscreen was permanently invisible. With my modifications, scrolling works as expected, and the "Close" button is not covered by the mask.
I just ran into the same issue and wound up writing my own class. It seems like serious overkill, but it was the only way I could find to do gradients with transparency. You can see my writeup and code example here
It basically comes down to a custom UIView that creates two images. One is a solid color, the other is a gradient that is used as an image mask. From there I applied the resulting image to the uiview.layer.content.
I hope it helps,
Joe
I hate to say it, but I think that you are into the CUSTOM UIView land. I think that I would try to implement this in a custom UIView overiding the drawRect routine.
With this, you could have that view, place on top of your actual scrollview, and have your gradient view (if you will) "pass-on" all touch events (i.e. relinquish first responder).

Fading out items in UICollectionView

I have a UICollectionView and I'm implementing sticky headers as per this link: http://blog.radi.ws/post/32905838158/sticky-headers-for-uicollectionview-using#notes
It works fantastically however my window has a background image applied, and my header views have a transparent background. Consequentially, when my items scroll above the header view, you can still see them.
Ideally I would fade out the cells with a gradient, to the point it is invisible by the time it appears behind the header view.
Thanks.
You haven't posted any code, so here's a go at it without looking at code. Just setup a mask layer over your UICollectionView's superview and you're good to go:
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = self.collectionView.superview.bounds;
gradient.colors = #[(id)[UIColor clearColor].CGColor, (id)[UIColor blackColor].CGColor];
// Here, percentage would be the percentage of the collection view
// you wish to blur from the top. This depends on the relative sizes
// of your collection view and the header.
gradient.locations = #[#0.0, #(percentage)];
self.collectionView.superview.layer.mask = gradient;
For this solution to work properly, you'd have to embed your collection view in a super view of its own.
For more information on layer masks, check out the documentation.
I created a fade mask over a collectionview that has this kind of effect. Maybe you're looking for something similar.
// This is in the UICollectionView subclass
private func addGradientMask() {
let coverView = GradientView(frame: self.bounds)
let coverLayer = coverView.layer as! CAGradientLayer
coverLayer.colors = [UIColor.whiteColor().colorWithAlphaComponent(0).CGColor, UIColor.whiteColor().CGColor, UIColor.whiteColor().colorWithAlphaComponent(0).CGColor]
coverLayer.locations = [0.0, 0.5, 1.0]
coverLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
coverLayer.endPoint = CGPoint(x: 1.0, y: 0.5)
self.maskView = coverView
}
// Declare this anywhere outside the sublcass
class GradientView: UIView {
override class func layerClass() -> AnyClass {
return CAGradientLayer.self
}
}
Additionally, you can make it sticky (i.e. it will always fade out the cells on the edge, instead of scrolling with the collection) by adding this to the collectionview subclass.
func scrollViewDidScroll(scrollView: UIScrollView) {
self.maskView?.frame = self.bounds
}
would seem to me the code you are following/using has done heavy work for you. As far I can see (not in position to test right now) just pass the alpha attribute:
layoutAttributes.zIndex = 1024;
layoutAttributes.frame = (CGRect){
.origin = origin,
.size = layoutAttributes.frame.size
like such
layoutAttributes.zIndex = 1024;
layoutAttributes.alpha = 0.1; //add this
layoutAttributes.frame = (CGRect){
.origin = origin,
.size = layoutAttributes.frame.size
instead of having a transparent background on your header, I would create a gradient transparent png and use that instead. It'd be a lot more efficient and easier handling the gradient with an image than doing it with code.
You should use a UIScrollViewDelegate for the CollectionView and use the scrollviewdidscroll method to create the fade, or subclass UICollectionViewFlowLayout.
Here is how I achieved that effect. I created in photoshop a gradient image, fading to the color of the background, which is in my case black. Here's what it looks like:
I placed the ImageView on my ViewController. I stretched it to the correct size and location of where I wanted and used AutoLayout constraints to lock it in place. (I had to use the arrow keys on my keyboard to move it around at times because clicking and dragging the location of the image tended to drop it inside of the CollectionView)
Click the ImageView, go to Editor -> Arrange -> Send to Front to make sure it sits on top of the CollectionView.
Image mode is Scale to Fill, and I have deselected User Interaction Enabled.
This will take some tweaking to get everything perfect but it works very well and looks nice.
I'm not entirely sure how you mean by with your background image and whatnot, but maybe make the gradient image part of the actual background image you have, so it blends in.

How to prevent backgroundColor of UISegmentedControl bleeding beyond segmented border

I've noticed that when I set a color for UISegmentedControl.backgroundColor, the color bleeds beyond the edges of the control (though not beyond the view's bounds). Here's an example with the segmented control's background color set to white and the container view's background color set to gray:
I've set the AutoLayout constraints of the segmented control such that the intrinsicContentSize should be used, but I haven't seen anyone else posting about this problem
Note that the image above is the best I've been able to get it to look... before that it was bleeding over by about 3-4px.
I've tried configuring the view to clipSubviews and the layer backing the UIView to masksToBounds, but I didn't expect that to fix the problem since I assume the bleeding is contained inside the view's/layer's bounds.
Any suggestions or advice appreciated. If not I'll just have to create images to back the UISegmentedControl that fix the bleeding, but that's annoying to have to maintain, to say the least.
Set the segment control's layer's corner radius to 4.0. It should help. You may need to import QuartzCore to be able to access the layer's properties.
segment.layer.cornerRadius = 4.0;
segment.clipsToBounds = YES;
Set segment control layer corner radius to 5. and ClipsToBounds YES .
segmentController.layer.cornerRadius = 5;
segmentController.clipsToBounds = YES;
Hope its work for you
the best result I could achieve in Swift:
segmentedControl.layer.cornerRadius = 4
let mask = CAShapeLayer()
mask.frame = CGRectMake(0, 0, segmentedControl.bounds.size.width-1, segmentedControl.bounds.size.height);
let maskPath = UIBezierPath(roundedRect: mask.frame,
byRoundingCorners: [.BottomLeft, .BottomRight, .TopLeft, .TopRight],
cornerRadii: CGSize(width: 4.0, height: 4.0))
mask.path = maskPath.CGPath
segmentedControl.layer.mask = mask

Resources