This gradient is what I'd like to achieve on dashed UIBezierPath.
Tried this code with no success.
let gradient = CAGradientLayer()
gradient.frame = outerPath.bounds
gradient.colors = [UIColor.red.cgColor, UIColor.yellow.cgColor]
// mask
let shapeMask = CAShapeLayer()
shapeMask.path = outerPath.cgPath
self.insertSublayer(gradient, at: 0)
Let the CAShapeLayer make a dashed line mask.
class
TheView: UIView {
required init?( coder aDecoder: NSCoder ) {
super.init( coder: aDecoder )
let outerPath = UIBezierPath( ovalIn: bounds.insetBy( dx: 20, dy: 20 ) )
let gradient = CAGradientLayer()
gradient.frame = bounds
gradient.colors = [ UIColor.red.cgColor, UIColor.yellow.cgColor ]
let shapeMask = CAShapeLayer()
shapeMask.path = outerPath.cgPath
shapeMask.lineWidth = 8
shapeMask.lineDashPhase = 0
shapeMask.lineDashPattern = [ 6, 2 ]
shapeMask.lineCap = .butt
shapeMask.lineJoin = .bevel
shapeMask.strokeColor = UIColor.black.cgColor // Any color
shapeMask.fillColor = nil
gradient.mask = shapeMask
layer.addSublayer( gradient )
}
}
I think the best way is filling every square's color by yourself.In this case, the start color is green, end color is red, so how to calculate the internal color?
You can see this demo:
typedef struct{
float red;
float green;
float blue;
} TFColor;
- (void)viewDidLoad {
[super viewDidLoad];
TFColor start = {0,1,0}; //green
TFColor end = {1,0,0}; //red
for (int i = 0; i<20; i++) {
UIView *square = [[UIView alloc] initWithFrame:CGRectMake(150, 20*i, 75, 20)];
//the lerp rate changes from 1 to 0.
TFColor lerpColor = [self lerp:(19-i)/19.0f first:start second:end];
square.backgroundColor = [UIColor colorWithRed:lerpColor.red green:lerpColor.green blue:lerpColor.blue alpha:1];
[self.view addSubview:square];
}
}
#define lerpNum(a,b,r) (a*r+(1.0f-r)*b)
-(TFColor)lerp:(CGFloat)rate first:(TFColor)firstColor second:(TFColor)secondColor{
TFColor result;
result.red = lerpNum(firstColor.red, secondColor.red, rate);
result.green = lerpNum(firstColor.green, secondColor.green, rate);
result.blue = lerpNum(firstColor.blue, secondColor.blue, rate);
return result;
}
You can use the angle of every square to get smooth lerp rate.
Related
I deep into the Core Animation and have some problem with layer masking
I try to make a complex UI layer with transparent things for study reasons
This view a have and put into the ViewController
public class TestView : UIView
{
public TestView()
{
Layer.Delegate = this;
Frame = new CGRect(100f,200f, 100f, 100f);
}
public override void LayoutSublayersOfLayer(CALayer layer)
{
base.LayoutSublayersOfLayer(layer);
var bounds = Bounds;
var circleFrame = new CGRect(20, 20, 60, 60);
var imageFrame = new CGRect(30, 30, 40, 40);
Layer.BorderWidth = 5;
Layer.BorderColor = UIColor.Red.CGColor;
Layer.CornerRadius = 4;
var gradientLayer = new CAGradientLayer();
gradientLayer.Colors = new[] { UIColor.Green.CGColor, UIColor.Red.CGColor };
gradientLayer.Frame = bounds;
Layer.AddSublayer(gradientLayer);
var maskOfGradientLayer = new CAShapeLayer();
var path = UIBezierPath.FromRoundedRect(circleFrame, 30);
path.UsesEvenOddFillRule = true;
maskOfGradientLayer.Path = path.CGPath;
maskOfGradientLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
maskOfGradientLayer.FillColor = UIColor.Black.CGColor;
maskOfGradientLayer.Frame = bounds;
gradientLayer.Mask = maskOfGradientLayer;
var maskOfMaskLayer = new CAShapeLayer();
maskOfMaskLayer.Frame = imageFrame;
maskOfMaskLayer.FillColor = UIColor.Black.CGColor;
maskOfMaskLayer.Contents = Bundles.ImageOff.CGImage;
Layer.AddSublayer(maskOfMaskLayer);
}
}
And that I have and this is exactly what I wanted.
But I also want can to make transparent in circle instead black color.
I tried to make like this maskOfGradientLayer.Mask = maskOfMaskLayer.
But this way maskOfMaskLayer do nothing! It's not working like mask must do.
What I should to do?
But I also want can to make transparent in circle instead black color.
Solution Exploratory Version:
You can also use UIBezierPath to draw what you want, and set to maskOfMaskLayer:
var maskOfMaskLayer = new CAShapeLayer();
maskOfMaskLayer.Frame = imageFrame;
maskOfMaskLayer.FillColor = UIColor.Black.CGColor;
maskOfMaskLayer.Contents = Bundles.ImageOff.CGImage;
Layer.AddSublayer(maskOfMaskLayer);
Up code repalced with follow:
UIBezierPath offCirclePath = new UIBezierPath();
// draw an arc
offCirclePath.AddArc(new CGPoint(50, 50), circleFrame.Width / 3, (nfloat)(1.75 * Math.PI), (nfloat)(1.25 * Math.PI), true);
//draw a line
offCirclePath.MoveTo(new CGPoint(50, 30));
offCirclePath.AddLineTo(new CGPoint(50, 45));
//set to maskOfMaskLayer
var maskOfMaskLayer = new CAShapeLayer();
maskOfMaskLayer.FillColor = UIColor.Clear.CGColor;
maskOfMaskLayer.Path = offCirclePath.CGPath;
maskOfMaskLayer.LineWidth = 5;
maskOfMaskLayer.StrokeColor = UIColor.White.CGColor;
maskOfMaskLayer.LineCap = new NSString("round");
Layer.AddSublayer(maskOfMaskLayer);
Other code not changed.
But I from starts thought about setting any custom image.
Solution Two:(Wrong direction)
I have tested that CAShapeLayer can not have this function to change color from image. CAShapeLayer Class
However , I found UIImageView Can do that.There is a TintColor propert of it.This property is from UiView .UIView.TintColor Property.
var maskOfMaskLayer = new CAShapeLayer();
maskOfMaskLayer.Frame = imageFrame;
maskOfMaskLayer.FillColor = UIColor.Black.CGColor;
maskOfMaskLayer.Contents = Bundles.ImageOff.CGImage;
Layer.AddSublayer(maskOfMaskLayer);
Change to:
UIImageView imageView = new UIImageView();
imageView.Frame = imageFrame;
imageView.Image = Bundles.ImageOff;
imageView.TintColor = UIColor.White;
AddSubview(imageView);
Right Solution :
Sorry for misunderstanding the real want effect,I update as follow:
Layer.Mask = maskOfMaskLayer;
If you use AddSublayer just overwrite your image on the Layer, and Layer.Mask is the opposite effect, it only shows the background that covers the part, and the rest of the area will be white.CALayer.Mask
All needed to do it is reverse image colors via Core Graphics, any color to transparent, transparent to any color. In this case, black color is enough
public static UIImage GetRevertImage(UIImage image, CGRect rect, CGRect cropFrame)
{
UIGraphics.BeginImageContextWithOptions(rect.Size, false, 1);
UIColor.Black.SetColor();
UIGraphics.RectFill(rect);
image.Draw(cropFrame, CGBlendMode.DestinationOut, 1);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
And set mask of mask layer to parent layer
Layer.Mask = maskOfMaskLayer;
And final version of code:
public class TestView : UIView
{
public TestView()
{
Layer.Delegate = this;
Frame = new CGRect(50f, 50f, 100f, 100f);
}
public override void LayoutSublayersOfLayer(CALayer layer)
{
base.LayoutSublayersOfLayer(layer);
var bounds = Bounds;
var circleFrame = new CGRect(20, 20, 60, 60);
var imageFrame = new CGRect(30, 30, 40, 40);
Layer.BorderWidth = 5;
Layer.BorderColor = UIColor.Red.CGColor;
Layer.CornerRadius = 4;
Layer.MasksToBounds = true;
var gradientLayer = new CAGradientLayer();
gradientLayer.Colors = new[] {UIColor.Green.CGColor, UIColor.Red.CGColor};
gradientLayer.Frame = bounds;
Layer.AddSublayer(gradientLayer);
var maskOfGradientLayer = new CAShapeLayer();
var path = UIBezierPath.FromRoundedRect(circleFrame, 30);
path.UsesEvenOddFillRule = true;
maskOfGradientLayer.Path = path.CGPath;
maskOfGradientLayer.FillRule = CAShapeLayer.FillRuleEvenOdd;
maskOfGradientLayer.FillColor = UIColor.Black.CGColor;
maskOfGradientLayer.Frame = bounds;
gradientLayer.Mask = maskOfGradientLayer;
var maskOfMaskLayer = new CALayer();
maskOfMaskLayer.Frame = bounds;
var image = UIImage.FromBundle("Turn");
var reversedImage = GetReverseImage(image, bounds, imageFrame);
maskOfMaskLayer.Contents = reversedImage.CGImage;
Layer.Mask = maskOfMaskLayer;
}
private static UIImage GetReverseImage(UIImage image, CGRect rect, CGRect cropFrame)
{
UIGraphics.BeginImageContextWithOptions(rect.Size, false, 1);
UIColor.Black.SetColor();
UIGraphics.RectFill(rect);
image.Draw(cropFrame, CGBlendMode.DestinationOut, 1);
var newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return newImage;
}
}
I want to create custom bar for displaying some progress, that must look something like this:
So, as you can see each bar has it's own gradient background. I want to use UICollectionView for this. But problem is to create gradient background for each individual cell. So is it possible somehow create ONE basic gradient for whole UICollectionView, and then mask it, to be visible inside UICollectionViewCell?
Okay, here is the example, background is the gradient layer with different colours are spread and above you can create a mask layer to appear only on the rectangular shapes, which gives the illusion of the different rectangular layers having different gradient, you can play with gradient to get your desired effect,
First you subclass the UIView or you can create directly, better you can create a subclass as I am doing in the example
obj-c
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self createGreadient];
}
return self;
}
//this create a grenadine with the rectangular mask layer
- (void)createGreadient
{
UIColor *theColor = [UIColor redColor];//[[UIColor alloc] initWithRed:146.0/255.0 green:146.0/255.0 blue:146.0/255.0 alpha:1];
CAGradientLayer *gradientLayer = [[CAGradientLayer alloc] init];
gradientLayer.frame = self.bounds;
//u can add your own colours to get your requirement
gradientLayer.colors = [NSArray arrayWithObjects:
(id)[theColor CGColor],
(id)[[theColor colorWithAlphaComponent:0.7f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.4f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.3f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.2f] CGColor],
(id)[[theColor colorWithAlphaComponent:0.1f] CGColor],
(id)[[UIColor clearColor] CGColor],nil];
[self.layer addSublayer:gradientLayer];
CAShapeLayer *layerMask = [[CAShapeLayer alloc] init];
layerMask.frame = self.bounds;
UIBezierPath *rectangularMaskPath = [self getRectangularMaskPathForCount:5];
layerMask.path = rectangularMaskPath.CGPath;
gradientLayer.mask = layerMask;
}
//this creates rectangular path, u can adjust the rectangular and u can
//pass different number of count as the progress proceeds
- (UIBezierPath *)getRectangularMaskPathForCount:(NSInteger)rectCount
{
UIBezierPath *path = [[UIBezierPath alloc] init];
int i = 0;
for(;i <= rectCount; i++)
{
UIBezierPath *aPath;
CGRect aRect = CGRectMake(20+ (i * 20), 20, 10, 100); //set the rectangular position to your requirement
aPath = [UIBezierPath bezierPathWithRect:aRect];
[path appendPath:aPath];
}
return path;
}
swift version
subclass the UIView and past the below code,
override init (frame : CGRect) {
super.init(frame : frame)
createGreadient()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createGreadient()
{
let color:UIColor = UIColor.red
let greadetLayer = CAGradientLayer.init()
greadetLayer.frame = self.bounds
greadetLayer.colors = [color.withAlphaComponent(0.8).cgColor,color.withAlphaComponent(0.7),color.withAlphaComponent(0.4).cgColor,color.withAlphaComponent(0.3).cgColor,color.withAlphaComponent(0.2),color.withAlphaComponent(0.1).cgColor]
self.layer .addSublayer(greadetLayer)
let rectangularMaskPath = self.creatrRectangularPathWithCount(countRect: 5)
let maskLayer:CAShapeLayer = CAShapeLayer()
maskLayer.frame = self.bounds
maskLayer.path = rectangularMaskPath.cgPath
greadetLayer.mask = maskLayer
}
func creatrRectangularPathWithCount(countRect:NSInteger) -> UIBezierPath {
let path : UIBezierPath = UIBezierPath()
for i in 0..<countRect {
let aPath = UIBezierPath.init(rect: CGRect(x: 20 + (i * 20), y:20, width: 10, height: 100))
path.append(aPath)
}
return path
}
You can use the above view like below,
in ViewController
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let customView:CustomView = CustomView(frame: CGRect(x: 20, y: 20, width: 300, height: 300))
self.view.addSubview(customView)
}
I want to create a circle with an inner circle that looks like the image below. I'm having trouble with the inner circle and I don't know how to create it so it's easy to adjust percentage (like the image is showing).
So far I have this CircleGraph class which can draw the ouster circle and an inner circle which can only draw 50 %.
import Foundation
import UIKit
class CircleGraph: UIView
{
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
super.drawRect(rect)
// Outer circle
Colors().getMainColor().setFill()
let outerPath = UIBezierPath(ovalInRect: rect)
outerPath.fill()
// inner circle so far
let percentage = 0.5
UIColor.whiteColor().setFill()
let circlePath = UIBezierPath(arcCenter: CGPoint(x: rect.height/2,y: rect.height/2), radius: CGFloat(rect.height/2), startAngle: CGFloat(-M_PI_2), endAngle:CGFloat(M_PI * 2 * percentage - M_PI_2), clockwise: true)
circlePath.fill()
}
}
Can anyone assist me?
What I want is something simliar to the image below:
I would go for the easy solution and create a UIView with a UIView and UILabel as subviews. If you use something like:
// To make it round
let width = self.frame.width
self.view.layer.cornerRadius = width * 0.5
self.view.layer.masksToBounds = true
for each of the sublayers. If you have set the background colour of the UIView's background layer to something like Red and the UIView layer above to have a whiteish background colour with alpha 0.5 than you already achieve this effect.
If you do not know how to proceed with this tip ill try to provide a code sample.
-- EDIT --
Here is the code sample:
import UIKit
class CircleView: UIView {
var percentage : Int?
var transparency : CGFloat?
var bottomLayerColor : UIColor?
var middleLayerColor : UIColor?
init(frame : CGRect, percentage : Int, transparency : CGFloat, bottomLayerColor : UIColor, middleLayerColor : UIColor) {
super.init(frame : frame)
self.percentage = percentage
self.transparency = transparency
self.bottomLayerColor = bottomLayerColor
self.middleLayerColor = middleLayerColor
viewDidLoad()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
viewDidLoad()
}
func viewDidLoad() {
let width = self.frame.width
let height = self.frame.height
let textFrame = CGRectMake(0, 0, width, height)
guard let percentage = self.percentage
else {
print("Error")
return
}
let newHeight = (CGFloat(percentage)/100.0)*height
let middleFrame = CGRectMake(0,height - newHeight, width, newHeight)
// Set Background Color
if let bottomLayerColor = self.bottomLayerColor {
self.backgroundColor = bottomLayerColor
}
// Make Bottom Layer Round
self.layer.cornerRadius = width * 0.5
self.layer.masksToBounds = true
// Create Middle Layer
let middleLayer = UIView(frame: middleFrame)
if let middleLayerColor = self.middleLayerColor {
middleLayer.backgroundColor = middleLayerColor
}
if let transparency = self.transparency {
middleLayer.alpha = transparency
}
// The Label
let percentageLayer = UILabel(frame: textFrame)
percentageLayer.textAlignment = NSTextAlignment.Center
percentageLayer.textColor = UIColor.whiteColor()
if let percentage = self.percentage {
percentageLayer.text = "\(percentage)%"
}
// Add Subviews
self.addSubview(middleLayer)
self.addSubview(percentageLayer)
}
}
To use in a View Controller:
let redColor = UIColor.redColor()
let blueColor = UIColor.blueColor()
let frame = CGRectMake(50, 50, 100, 100)
// 50% Example
let circleView = CircleView(frame: frame, percentage: 50, transparency: 0.5, bottomLayerColor: redColor, middleLayerColor: blueColor)
self.view.addSubview(circleView)
// 33% Example
let newFrame = CGRectMake(50, 150, 120, 120)
let newCircleView = CircleView(frame: newFrame, percentage: 33, transparency: 0.7, bottomLayerColor: UIColor.redColor(), middleLayerColor: UIColor.whiteColor())
self.view.addSubview(newCircleView)
This will yield something like this:
Here is my class and it'll draw a circle, it looks like this:
class OvalLayer: CAShapeLayer {
let animationDuration: CFTimeInterval = 0.3
override init() {
super.init()
fillColor = Colors.green.CGColor
path = ovalPathSmall.CGPath
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var ovalPathStart: UIBezierPath {
let path = UIBezierPath(ovalInRect: CGRect(x: 0.0, y: 0.0, width: 100.0, height: 100.0))
return path
}
}
Now I need to add a text to middle of this circle, I tried to find it on google but nothing that works fine. I am not sure if it's possible or not, can anyone help me if it's possible?
I guess you should add CATextLayer as a sublayer to CALayer... That works fine that way: try adding CAShapeLayer first, and then CATextLayer (to same CALayer parent layer), for example in following order...
// assume self - is UIView instance
self.layer.addSublayer(shapedLayer) // shapedLayer - CAShapeLayer instance
self.layer.addSublayer(textLayer) // textLayer - CATextLayer instance
Swift 3.0
let label = UILabel()
label.font = UIFont(name: "Helvetica-Bold", size: 12)
label.frame = CGRect(x: OvalLayer.frame.origin.x + (circleWidth/2), y: OvalLayer.frame.origin.y, width: OvalLayer.bounds.width, height: OvalLayer.bounds.height)
label.text = "Hello"
label.textColor = UIColor.red
label.isHidden = false
OvalLayer.addSublayer(label.layer)
You just need to get the center of your UIBezierPath and add a label or a CATextLayer to your current layer.
let center : CGPoint = CGPoint(x: CGRectGetMidX(ovalPathStart.bounds), y: CGRectGetMidX(ovalPathStart.bounds))
Now, create a UILabel or CATextLayer and set the center.
Text on CAShapeLayer Using CATextLayer
Here i am create CAShapeLayer object and i am adding CATextLayer to CAShapeLayer
Here numberOfArcsCount means some 8
CAShapeLayer *progressLayer = [[CAShapeLayer alloc] init];
[progressLayer setPath:bezierPath.CGPath];
CATextLayer* text = [CATextLayer new];
for (int i = 1; i <= numberOfArcs.count; i++) {
text.string = [NSString stringWithFormat:#"%i", i];
text.font = (__bridge CFTypeRef _Nullable)([UIFont fontWithName:#"akaChen" size:42]);
text.font = (__bridge CFTypeRef _Nullable)([UIFont boldSystemFontOfSize:15]);
text.fontSize=25;
text.frame = CGRectMake(0,0,40,40);
text.position = CGPointMake(CGRectGetMidX(progressLayer.frame) ,CGRectGetMidY(progressLayer.frame) );
CGFloat vert = CGRectGetMidY(progressLayer.frame) / CGRectGetHeight(text.frame);
text.anchorPoint = CGPointMake(0.5, vert );
text.alignmentMode = kCAAlignmentCenter;
text.foregroundColor = [[UIColor whiteColor] CGColor];
[progressLayer addSublayer:text];
}
This way to add label to layer :
labelFrame - CGRect
someString - String
layer - your layer
let label = CATextLayer()
label.frame = labelFarme
label.string = someString
layer.addSublayer(label)
I've made a little research about my problem and unfortunately there was no solution for my problem.
The closest was Fade UIImageView as it approaches the edges of a UIScrollView but it's still not for me.
I want my table to apply an "invisibility gradient" on the top. If the cell is at a 50px distance from the top edge it starts to vanish. The closer it is to the upper edge, the more invisible the part is. The cells height is about 200 pixels, so the lower part of the cell need to be visible in 100%. But nevermind - I need a table view (or table view container) to do this task, because similar tables can display other cells.
If the table is a subview of a solid color view, I can achieve that by adding an image which is a horizontal gradient that I can streach to any width. The top pixel of that image starts with the exact color of the background, and going down the same color has less alpha.
But...
we have a UITableView with transparent color. Below the table there is no solid color, but a pattern image/texture, that can also be different on other screens of the app.
Do you have any Idea how I can achieve this behaviour?
Regards
I took this tutorial and made some changes and additions:
It now works on all tableviews - even if they are part of bigger screen.
It works regardless of the background or whatever is behind the tableview.
The mask changes depends on the position of the table view - when scrolled to top only the bottom faded, in when scrolled to bottom only top is faded...
1. Start by importing QuartzCore and setting a mask layer in your controller:
EDIT: No need for reference to CAGradientLayer in class.
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface mViewController : UIViewController
.
.
#end
2. Add this to viewWillAppear viewDidLayoutSubviews:
(See #Darren's comment on this one)
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
if (!self.tableView.layer.mask)
{
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.locations = #[[NSNumber numberWithFloat:0.0],
[NSNumber numberWithFloat:0.2],
[NSNumber numberWithFloat:0.8],
[NSNumber numberWithFloat:1.0]];
maskLayer.bounds = CGRectMake(0, 0,
self.tableView.frame.size.width,
self.tableView.frame.size.height);
maskLayer.anchorPoint = CGPointZero;
self.tableView.layer.mask = maskLayer;
}
[self scrollViewDidScroll:self.tableView];
}
3. Make sure you are a delegate of UIScrollViewDelegate by adding it in the .h of your controller:
#interface mViewController : UIViewController <UIScrollViewDelegate>
4. To finish, implement scrollViewDidScroll in your controller .m:
#pragma mark - Scroll View Delegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGColorRef outerColor = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
CGColorRef innerColor = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
NSArray *colors;
if (scrollView.contentOffset.y + scrollView.contentInset.top <= 0) {
//Top of scrollView
colors = #[(__bridge id)innerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
} else if (scrollView.contentOffset.y + scrollView.frame.size.height
>= scrollView.contentSize.height) {
//Bottom of tableView
colors = #[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)innerColor];
} else {
//Middle
colors = #[(__bridge id)outerColor, (__bridge id)innerColor,
(__bridge id)innerColor, (__bridge id)outerColor];
}
((CAGradientLayer *)scrollView.layer.mask).colors = colors;
[CATransaction begin];
[CATransaction setDisableActions:YES];
scrollView.layer.mask.position = CGPointMake(0, scrollView.contentOffset.y);
[CATransaction commit];
}
Again: most of the solution is from this tutorial in cocoanetics.
This is a translation of Aviel Gross's answer to Swift
import UIKit
class mViewController: UIViewController, UIScrollViewDelegate {
//Emitted boilerplate code
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.tableView.layer.mask == nil {
//If you are using auto layout
//self.view.layoutIfNeeded()
let maskLayer: CAGradientLayer = CAGradientLayer()
maskLayer.locations = [0.0, 0.2, 0.8, 1.0]
let width = self.tableView.frame.size.width
let height = self.tableView.frame.size.height
maskLayer.bounds = CGRect(x: 0.0, y: 0.0, width: width, height: height)
maskLayer.anchorPoint = CGPoint.zero
self.tableView.layer.mask = maskLayer
}
scrollViewDidScroll(self.tableView)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
var colors = [CGColor]()
if scrollView.contentOffset.y + scrollView.contentInset.top <= 0 {
colors = [innerColor, innerColor, innerColor, outerColor]
} else if scrollView.contentOffset.y + scrollView.frame.size.height >= scrollView.contentSize.height {
colors = [outerColor, innerColor, innerColor, innerColor]
} else {
colors = [outerColor, innerColor, innerColor, outerColor]
}
if let mask = scrollView.layer.mask as? CAGradientLayer {
mask.colors = colors
CATransaction.begin()
CATransaction.setDisableActions(true)
mask.position = CGPoint(x: 0.0, y: scrollView.contentOffset.y)
CATransaction.commit()
}
}
//Emitted boilerplate code
}
Swift version of #victorfigol's excellent solution:
class FadingTableView : UITableView {
var percent = Float(0.05)
private let outerColor = UIColor(white: 1.0, alpha: 0.0).cgColor
private let innerColor = UIColor(white: 1.0, alpha: 1.0).cgColor
override func awakeFromNib() {
super.awakeFromNib()
addObserver(self, forKeyPath: "bounds", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if object is FadingTableView && keyPath == "bounds" {
initMask()
}
}
deinit {
removeObserver(self, forKeyPath:"bounds")
}
override func layoutSubviews() {
super.layoutSubviews()
updateMask()
}
func initMask() {
let maskLayer = CAGradientLayer()
maskLayer.locations = [0.0, NSNumber(value: percent), NSNumber(value:1 - percent), 1.0]
maskLayer.bounds = CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height)
maskLayer.anchorPoint = CGPoint.zero
self.layer.mask = maskLayer
updateMask()
}
func updateMask() {
let scrollView : UIScrollView = self
var colors = [CGColor]()
if scrollView.contentOffset.y <= -scrollView.contentInset.top { // top
colors = [innerColor, innerColor, innerColor, outerColor]
}
else if (scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height { // bottom
colors = [outerColor, innerColor, innerColor, innerColor]
}
else {
colors = [outerColor, innerColor, innerColor, outerColor]
}
if let mask = scrollView.layer.mask as? CAGradientLayer {
mask.colors = colors
CATransaction.begin()
CATransaction.setDisableActions(true)
mask.position = CGPoint(x: 0.0, y: scrollView.contentOffset.y)
CATransaction.commit()
}
}
}
This is my version of the fading table view by inheriting UITableView. Tested for iOS 7 & 8.
There is no need to implement scrollViewDidScroll, layoutSubviews can be used instead.
By observing for bounds changes, the mask is
always properly placed when the rotation changes.
You can use the percent parameter to change how much fading you want at the edges, I
find a small value looking better in some cases.
CEFadingTableView.m
#import "CEFadingTableView.h"
#interface CEFadingTableView()
#property (nonatomic) float percent; // 1 - 100%
#end
#implementation CEFadingTableView
- (void)awakeFromNib
{
[super awakeFromNib];
self.percent = 5.0f;
[self addObserver:self forKeyPath:#"bounds" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if(object == self && [keyPath isEqualToString:#"bounds"])
{
[self initMask];
}
}
- (void)dealloc
{
[self removeObserver:self forKeyPath:#"bounds"];
}
- (void)layoutSubviews
{
[super layoutSubviews];
[self updateMask];
}
- (void)initMask
{
CAGradientLayer *maskLayer = [CAGradientLayer layer];
maskLayer.locations = #[#(0.0f), #(_percent / 100), #(1 - _percent / 100), #(1.0f)];
maskLayer.bounds = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
maskLayer.anchorPoint = CGPointZero;
self.layer.mask = maskLayer;
[self updateMask];
}
- (void)updateMask
{
UIScrollView *scrollView = self;
CGColorRef outer = [UIColor colorWithWhite:1.0 alpha:0.0].CGColor;
CGColorRef inner = [UIColor colorWithWhite:1.0 alpha:1.0].CGColor;
NSArray *colors = #[(__bridge id)outer, (__bridge id)inner, (__bridge id)inner, (__bridge id)outer];
if(scrollView.contentOffset.y <= 0) // top
{
colors = #[(__bridge id)inner, (__bridge id)inner, (__bridge id)inner, (__bridge id)outer];
}
else if((scrollView.contentOffset.y + scrollView.frame.size.height) >= scrollView.contentSize.height) // bottom
{
colors = #[(__bridge id)outer, (__bridge id)inner, (__bridge id)inner, (__bridge id)inner];
}
((CAGradientLayer *)scrollView.layer.mask).colors = colors;
[CATransaction begin];
[CATransaction setDisableActions:YES];
scrollView.layer.mask.position = CGPointMake(0, scrollView.contentOffset.y);
[CATransaction commit];
}
#end