I'm trying to generate a view with a gradient color background (A solid color to transparent) at runtime. Is there a way of doing that?
相关问题
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
- Get the NSRange for the visible text after scroll
相关文章
- 现在使用swift开发ios应用好还是swift?
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- Swift - hide pickerView after value selected
- How do you detect key up / key down events from a
- didBeginContact:(SKPhysicsContact *)contact not in
- Attempt to present UIAlertController on View Contr
A Swift Approach
This answer builds on the answers above and provides implementation for dealing with the problem of the gradient not being properly applied during rotation. It satisfies this problem by changing the gradient layer to a square so that rotation in all directions results in a correct gradient. The function signature includes a Swift variadic argument that allows one to pass in as many CGColorRef's (CGColor) as needed (see sample usage). Also provided is an example as a Swift extension so that one can apply a gradient to any UIView.
To use:
in viewDidLoad...
Extension implementation
Extension use-case example:
Which means the gradient background can now be applied to any UIControl since all controls are UIViews (or a subclass) and all UIViews have CALayers.
Swift 4
Extension implementation
Extension use-case example:
Since I only needed one type of gradient throughout my app I created a subclass of UIView and preconfigured the gradient layer on initialization with fixed colors. The initializers of UIView call the configureGradientLayer-method, which configures the CAGradientLayer:
DDGradientView.h:
DDGradientView.m:
What you are looking for is
CAGradientLayer
. EveryUIView
has a layer - into that layer you can add sublayers, just as you can add subviews. One specific type is theCAGradientLayer
, where you give it an array of colors to gradiate between.One example is this simple wrapper for a gradient view:
http://oleb.net/blog/2010/04/obgradientview-a-simple-uiview-wrapper-for-cagradientlayer/
Note that you need to include the QuartZCore framework in order to access all of the layer parts of a UIView.
I have implemented this in my code.
Now I can see a gradient on my view.
USAGE
Try This it worked like a charm for me,
Objective C
I have set RGB gradient background Color to UIview
UPDATED :- Swift3 +
Code :-
You can add starting and end point of gradient color.
For more details description refer CAGradientLayer Doc
Hope this is help for some one .