I want the bottom (not quite half) of my UIView to be a different color than the top.
I'm wondering if I should create a CGRect and then color that? Is this along the right track?
- (void)drawRect:(CGRect)rect {
CGRect aRect = CGRectMake(x, y, width, height);
// Fill the rectangle with grey
[[UIColor greyColor] setFill];
UIRectFill( rect );
}
With Swift 4 and iOS 11, according to your needs, you may choose one of the two following ways in order to solve your problem.
#1. Draw and fill a specified
CGRect
instance with aUIColor
instance inside aUIView
subclass usingUIRectFill(_:)
functionUIKit
provides aUIRectFill(_:)
function.UIRectFill(_:)
has the following declaration:The following Playground code shows how to use
UIRectFill(_:)
:#2. Draw and fill a specified
CGRect
instance with aUIColor
instance inside aUIView
subclass usingCGContext
'sfill(_:)
methodCGContext
has a method calledfill(_:)
.fill(_:)
has the following declaration:The following Playground code shows how to use
fill(_:)
:Yes, as you are already overriding drawRect method, this will do.
Change the values inside the frames as you wish.
You can do a CGRect and clip a part of a portion to fill.
But why won't try two different UIViews placed next to each other?
Bharath
Override the drawRect method of your UIView Subclass. The following code will make the top half of your view black and the bottom half of your view red.
NOTE: Also you can only override the drawRect: method when you subclass a UIView. Based on your comment view I have a feeling this is not what you are doing.
You can also add an CALayer as a sub layer to your view. Include CoreGraphics and QuartzCore frameworks and create a CGRect with the desired form factor in your drawRect method. Instantiate a CALayer with the rect and add it to the view's layer using [self.layer addSublayer:theLayer]. Before adding it use the CALayer's -setBackgroundColor: method.
If this is inside of a View Controller instead of a View subclass, do exactly the same in the viewDidLoad method.
Bryan
You can use this code. Please change the CGRect according to your desire.
The following link may help you more. http://www.raywenderlich.com/32925/core-graphics-tutorial-shadows-and-gloss