Reputation: 381
I am trying to make a custom UISlider by creating a class that extends UIControl. I am having issues trying to fill and stroke CGRects using core graphics. I am able to correctly stroke and fill a CGRect at position (0,0), but cannot at any other position.
Here is what I see when I draw my UISlider at (0,0)
Here is what I see when I draw my UISlider at (%10,%10)
my slider is made in in the AppDelegate
var slider:RGBSlider
slider = RGBSlider(frame: CGRectMake(bounds.width * 0.1, bounds.height * 0.1, bounds.width * 0.6, bounds.height * 0.15), leftColor: UIColor.blackColor(), rightColor: UIColor.redColor())
here is the class declaration:
class RGBSlider: UIControl
{
//member vars
private var _sliderRec: CGRect = CGRectZero
private var _cursorRec: CGRect = CGRectZero
private var _gradient: CAGradientLayer
//initlizer
init(frame: CGRect, leftColor: UIColor, rightColor: UIColor)
{
_sliderRec = frame
//and this does not
//_sliderRec.origin.x = frame.origin.x
//_sliderRec.origin.y = frame.origin.y
//this works for some reason
//_sliderRec.origin.x = 0
//_sliderRec.origin.y = 0
_gradient = CAGradientLayer()
_gradient.colors = [leftColor, rightColor]
_gradient.locations = [0.0, 255.0]
super.init(frame: _sliderRec)
}
required init(coder aDecoder: NSCoder)
{
fatalError("init(coder:) has not been implemented")
}
//defines how to draw the slider
override func drawRect(rect: CGRect)
{
let context: CGContext! = UIGraphicsGetCurrentContext()
let strokeSize:Float = 3.0
var smallerRec = CGRectMake( _sliderRec.origin.x + CGFloat(strokeSize/2), _sliderRec.origin.y + CGFloat(strokeSize/2), (_sliderRec.size.width - CGFloat(strokeSize)), (_sliderRec.size.height - CGFloat(strokeSize)) )
//fills the rectangle
CGContextAddRect(context, smallerRec)
CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor)
CGContextDrawPath(context, kCGPathFill)
//stroke in the rectangle
CGContextAddRect(context, _sliderRec)
CGContextSetStrokeColorWithColor(context, _gradient.colors[1].CGColor)
CGContextStrokeRectWithWidth(context, _sliderRec, CGFloat(strokeSize))
CGContextStrokeRect(context, _sliderRec)
CGContextDrawPath(context, kCGPathStroke)
}
}
Why is my slider not drawing at the origin of my CGRect when it is not at the origin? How can I fix this? Thank You!
Upvotes: 1
Views: 109
Reputation: 1336
Try using bounds
in drawRect in place of _sliderRec
. The _sliderRec
is the frame of the view which is its position in its superview. When drawing within the view you'll want to use the view's bounds
property instead.
Upvotes: 3