objective-c create and stroke an arc with CG - core-graphics

I was following a Ray Wenderlich tutorial on creating arcs:
http://www.raywenderlich.com/33193/core-graphics-tutorial-arcs-and-paths
-what I am looking to do is begin at point a (a fixed point) and locate where the user touches the screen, if it is + point A, then I want to draw an arc to that point. Though I don't return any errors I also don't get the path to be stroked. Could someone review the code below and see what I am doing wrong?
#implementation KIP_Arc
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void) setArc {
//set the frame
float frameX = _startPoint.x;
float frameY = _startPoint.y;
float frameW = _endPoint.x;
float frameH = 50.0;
[self setFrame:CGRectMake(frameX, frameY, frameW, frameH)];
self.backgroundColor = [UIColor clearColor];
}
- (BOOL)isFlipped {
return YES;
}
- (void)drawRect:(CGRect)rect {
[[UIColor blackColor] set];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGRect arcRect = self.frame;
CGMutablePathRef arcPath = [self createArcPathFromBottomOfRect:arcRect:25.0];
CGContextAddPath(context, arcPath);
CGContextClip(context);
CGContextFillPath(context);
CGContextRestoreGState(context);
CFRelease(arcPath);
}
- (CGMutablePathRef) createArcPathFromBottomOfRect : (CGRect) rect : (CGFloat) arcHeight {
CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height - arcHeight, rect.size.width, arcHeight);
CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
CGPoint arcCenter = CGPointMake(arcRect.origin.x + arcRect.size.width/2, arcRect.origin.y + arcRadius);
CGFloat angle = acos(arcRect.size.width / (2*arcRadius));
CGFloat startAngle = radians(180) + angle;
CGFloat endAngle = radians(360) - angle;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle, endAngle, 0);
CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGPathAddLineToPoint(path, NULL, CGRectGetMinX(rect), CGRectGetMaxY(rect));
return path;
}
static inline double radians (double degrees){
return degrees * M_PI/180;
}

CGContextClip, as a side effect, empties the current path. When you call CGContextFillPath immediately afterward, the current path is empty, so you fill nothing.
As its name implies, CGContextFillPath restricts itself to the context's current path. (If it didn't, its name would just be CGContextFill.) So, you don't need to clip.
Drop the CGContextClip call and just use CGContextFillPath.

Related

Objective-C Moving object along curved path

I've looked at other SO answers to this quesiton, particularly Brad Larson's but I am still not getting any results. I'm not sure if I am approaching this the correct way. In my app, when a user touches the screen I capture the point and create an arc from a fixed point to that touch point. I then want to move a UIView along that arc.
Here's my code:
ViewController.m
//method to "shoot" object - KIP_Projectile creates the arc, KIP_Character creates the object I want to move along the arc
...
//get arc for trajectory
KIP_Projectile* vThisProjectile = [[KIP_Projectile alloc] initWithFrame:CGRectMake(51.0, fatElvisCenterPoint-30.0, touchPoint.x, 60.0)];
vThisProjectile.backgroundColor = [UIColor clearColor];
[self.view addSubview:vThisProjectile];
...
KIP_Character* thisChar = [[KIP_Character alloc] initWithFrame:CGRectMake(51, objCenterPoint-5, imgThisChar.size.width, imgThisChar.size.height)];
thisChar.backgroundColor = [UIColor clearColor];
thisChar.charID = charID;
thisChar.charType = 2;
thisChar.strCharType = #"Projectile";
thisChar.imgMyImage = imgThisChar;
thisChar.myArc = vThisProjectile;
[thisChar buildImage];
[thisChar traceArc];
in KIP_Projectile I build the arc using this code:
- (CGMutablePathRef) createArcPathFromBottomOfRect : (CGRect) rect : (CGFloat) arcHeight {
CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height - arcHeight, rect.size.width, arcHeight);
CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) / (8*arcRect.size.height));
CGPoint arcCenter = CGPointMake(arcRect.origin.x + arcRect.size.width/2, arcRect.origin.y + arcRadius);
CGFloat angle = acos(arcRect.size.width / (2*arcRadius));
CGFloat startAngle = radians(180) + angle;
CGFloat endAngle = radians(360) - angle;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle, endAngle, 0);
return path;
}
- (void)drawRect:(CGRect)rect {
CGContextRef currentContext = UIGraphicsGetCurrentContext();
_myArcPath = [self createArcPathFromBottomOfRect:self.bounds:30.0];
CGContextSetLineWidth(currentContext, 1);
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
CGContextSetStrokeColor(currentContext, red);
CGContextAddPath(currentContext, _myArcPath);
CGContextStrokePath(currentContext);
}
Works fine. The arc is displayed with a red stroke on the screen.
In KIP_Character, which has been passed it's relevant arc, I am using this code but getting no results.
- (void) traceArc {
CGMutablePathRef myArc = _myArc.myArcPath;
// Set up path movement
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:#"position"];
pathAnimation.calculationMode = kCAAnimationPaced;
pathAnimation.fillMode = kCAFillModeForwards;
pathAnimation.removedOnCompletion = NO;
pathAnimation.path = myArc;
CGPathRelease(myArc);
[self.layer addAnimation:pathAnimation forKey:#"savingAnimation"];
}
Any help here would be appreciated.

Use value from UISlider to change another variable?

So I'm still learning this Objective C lark and i've hit a stump. All I want to do is use the value from Sliderchanged to populate the 'CGFloat lineWidth =', Hopefully to have the end result of changing the width of the crumbPath line...
******************EDIT*********************
CrumbPathView.h
#import "CrumbPathView.h"
#import "CrumbPath.h"
#import "FirstViewController.h"
#interface CrumbPathView (FileInternal)
- (CGPathRef)newPathForPoints:(MKMapPoint *)points
pointCount:(NSUInteger)pointCount
clipRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale;
#end
#implementation CrumbPathView
-(IBAction)sliderChanged:(UISlider *)sender
{
NSLog(#"slider value = %f", sender.value);
}
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
CrumbPath *crumbs = (CrumbPath *)(self.overlay);
CGFloat lineWidth = 30;
// outset the map rect by the line width so that points just outside
// of the currently drawn rect are included in the generated path.
MKMapRect clipRect = MKMapRectInset(mapRect, -lineWidth, -lineWidth);
[crumbs lockForReading];
CGPathRef path = [self newPathForPoints:crumbs.points
pointCount:crumbs.pointCount
clipRect:clipRect
zoomScale:zoomScale];
[crumbs unlockForReading];
if (path != nil)
{
CGContextAddPath(context, path);
CGContextSetRGBStrokeColor(context, 0.0f, 0.0f, 1.0f, 0.5f);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, lineWidth);
CGContextStrokePath(context);
CGPathRelease(path);
}
}
#end
#implementation CrumbPathView (FileInternal)
static BOOL lineIntersectsRect(MKMapPoint p0, MKMapPoint p1, MKMapRect r)
{
double minX = MIN(p0.x, p1.x);
double minY = MIN(p0.y, p1.y);
double maxX = MAX(p0.x, p1.x);
double maxY = MAX(p0.y, p1.y);
MKMapRect r2 = MKMapRectMake(minX, minY, maxX - minX, maxY - minY);
return MKMapRectIntersectsRect(r, r2);
}
#define MIN_POINT_DELTA 5.0
- (CGPathRef)newPathForPoints:(MKMapPoint *)points
pointCount:(NSUInteger)pointCount
clipRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
{
// The fastest way to draw a path in an MKOverlayView is to simplify the
// geometry for the screen by eliding points that are too close together
// and to omit any line segments that do not intersect the clipping rect.
// While it is possible to just add all the points and let CoreGraphics
// handle clipping and flatness, it is much faster to do it yourself:
//
if (pointCount < 2)
return NULL;
CGMutablePathRef path = NULL;
BOOL needsMove = YES;
#define POW2(a) ((a) * (a))
// Calculate the minimum distance between any two points by figuring out
// how many map points correspond to MIN_POINT_DELTA of screen points
// at the current zoomScale.
double minPointDelta = MIN_POINT_DELTA / zoomScale;
double c2 = POW2(minPointDelta);
MKMapPoint point, lastPoint = points[0];
NSUInteger i;
for (i = 1; i < pointCount - 1; i++)
{
point = points[i];
double a2b2 = POW2(point.x - lastPoint.x) + POW2(point.y - lastPoint.y);
if (a2b2 >= c2) {
if (lineIntersectsRect(point, lastPoint, mapRect))
{
if (!path)
path = CGPathCreateMutable();
if (needsMove)
{
CGPoint lastCGPoint = [self pointForMapPoint:lastPoint];
CGPathMoveToPoint(path, NULL, lastCGPoint.x, lastCGPoint.y);
}
CGPoint cgPoint = [self pointForMapPoint:point];
CGPathAddLineToPoint(path, NULL, cgPoint.x, cgPoint.y);
}
else
{
// discontinuity, lift the pen
needsMove = YES;
}
lastPoint = point;
}
}
#undef POW2
// If the last line segment intersects the mapRect at all, add it unconditionally
point = points[pointCount - 1];
if (lineIntersectsRect(lastPoint, point, mapRect))
{
if (!path)
path = CGPathCreateMutable();
if (needsMove)
{
CGPoint lastCGPoint = [self pointForMapPoint:lastPoint];
CGPathMoveToPoint(path, NULL, lastCGPoint.x, lastCGPoint.y);
}
CGPoint cgPoint = [self pointForMapPoint:point];
CGPathAddLineToPoint(path, NULL, cgPoint.x, cgPoint.y);
}
return path;
}
#end
CrumbPathView.h
#import <MapKit/MapKit.h>
#import <UIKit/UIKit.h>
#interface CrumbPathView : MKOverlayView
{
}
- (IBAction)sliderChanged:(id)sender;
#end
I've added the rest of the code from the .h & .m ...
I think you are mostly there. Your slider is probably stored in a propery...just check it like you would any other property when you need its value.
Example:
-(IBAction)sliderChanged:(UISlider *)sender
{
//[self drawMapRect...]
}
-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:CGContextRef)context
{
CrumbPath *crumbs = (CrumbPath *)(self.overlay);
CGFloat lineWidth = self.mySliderControl.value;
//Do something with lineWidth
}
Did you tried this ?
-(IBAction)sliderChanged:(UISlider *)sender
{
NSLog(#"slider value = %f", sender.value);
CrumbPath *crumbs = (CrumbPath *)(self.overlay);
CGFloat lineWidth = (UISlider*)sender.value;
//Set value on crumbpath using slider value
}
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
CrumbPath *crumbs = (CrumbPath *)(self.overlay);
}

UITextview: how to indent the text?

Ok i'm trying to create a ruled notebook view.
The code to create this is below
#interface QuickNoteNoteTextView ()
#property (nonatomic) CGPoint startPoint;
#property (nonatomic) CGPoint endPoint;
#property (nonatomic, retain) UIColor *lineColor;
#end
#implementation QuickNoteNoteTextView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
// Get the graphics context
CGContextRef ctx = UIGraphicsGetCurrentContext();
[super drawRect:rect];
// Get the height of a single text line
NSString *alpha = #"ABCD";
CGSize textSize = [alpha sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:NSLineBreakByWordWrapping ];
NSUInteger height = textSize.height;
// Get the height of the view or contents of the view whichever is bigger
textSize = [self.text sizeWithFont:self.font constrainedToSize:self.contentSize lineBreakMode:NSLineBreakByWordWrapping ];
NSUInteger contentHeight = (rect.size.height > textSize.height) ? (NSUInteger)rect.size.height : textSize.height;
NSUInteger offset = 6 + height; // MAGIC Number 6 to offset from 0 to get first line OK ???
contentHeight += offset;
// Draw ruled lines
CGContextSetRGBStrokeColor(ctx, 0, 0, 0, 1);
for(int i=offset;i < contentHeight;i+=height) {
CGPoint lpoints[2] = { CGPointMake(0, i), CGPointMake(rect.size.width, i) };
CGContextStrokeLineSegments(ctx, lpoints, 2);
}
//vertical line
self.startPoint = CGPointMake(22.0, self.frame.size.height * -1);
self.endPoint = CGPointMake(22.0, self.frame.size.height * 2);
self.lineColor = [UIColor redColor];
CGContextSetShouldAntialias(ctx, NO);
CGContextSetStrokeColorWithColor(ctx, [self.lineColor CGColor]);
CGContextSetLineWidth(ctx, 1);
CGContextBeginPath(ctx);
CGContextMoveToPoint(ctx, self.startPoint.x, self.startPoint.y);
CGContextAddLineToPoint(ctx, self.endPoint.x, self.endPoint.y);
CGContextMoveToPoint(ctx, self.startPoint.x + 2.0f, self.startPoint.y);
CGContextAddLineToPoint(ctx, self.endPoint.x + 2.0f, self.endPoint.y);
CGContextDrawPath(ctx, kCGPathStroke);
}
This code correctly draws horizontal ruled lines in a UITextview and a vertical margin line on the left.
The last thing i'm trying to do is shift the text in my textview right so that it sits to the right of the vertical line.
Any ideas?
OK I solved the problem by using contentInset to push the text to the right by 20 pixels, then amended my drawRect to extend the horizontal line by -20 to account for the contentInset

ios Help Screen semi-transparent overlay

Wondering if anyone can shed some light on how to create a semi-transparent Help screen on an ipad or iphone app? Something similar to Googles app.
I have a splitViewController and I want to overlay a see-through black overlay on top of the splitViewController where I can show Help information about each item you can click in the splitViewController.
I followed http://cocoawithlove.com/2009/04/showing-message-over-iphone-keyboard.html which gets me the overlay, but I am now adding clickable UIViews (eg a close button to dismiss the overlay). The issue is when I setup touchesEnded:withEvent I cannot seem to convert clicks from the main LoadingView to closeButton to see what was actually clicked?
See the touches ended at the end of the code
================================================================
#import "HelpView.h"
#import <QuartzCore/QuartzCore.h>
//
CGPathRef NewPathWithRoundRect(CGRect rect, CGFloat cornerRadius)
{
//
// Create the boundary path
//
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path, NULL,
rect.origin.x,
rect.origin.y + rect.size.height - cornerRadius);
// Top left corner
CGPathAddArcToPoint(path, NULL,
rect.origin.x,
rect.origin.y,
rect.origin.x + rect.size.width,
rect.origin.y,
cornerRadius);
// Top right corner
CGPathAddArcToPoint(path, NULL,
rect.origin.x + rect.size.width,
rect.origin.y,
rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height,
cornerRadius);
// Bottom right corner
CGPathAddArcToPoint(path, NULL,
rect.origin.x + rect.size.width,
rect.origin.y + rect.size.height,
rect.origin.x,
rect.origin.y + rect.size.height,
cornerRadius);
// Bottom left corner
CGPathAddArcToPoint(path, NULL,
rect.origin.x,
rect.origin.y + rect.size.height,
rect.origin.x,
rect.origin.y,
cornerRadius);
// Close the path at the rounded rect
CGPathCloseSubpath(path);
return path;
}
#implementation HelpView
#synthesize closeButton = _closeButton;
- (id)loadingViewInView:(UIView *)aSuperview
{
HelpView *loadingView =
[[HelpView alloc] initWithFrame:[aSuperview bounds]];
if (!loadingView)
{
return nil;
}
loadingView.opaque = NO;
loadingView.autoresizingMask =
UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[aSuperview addSubview:loadingView];
const CGFloat DEFAULT_LABEL_WIDTH = 100.0;
const CGFloat DEFAULT_LABEL_HEIGHT = 40.0;
CGRect labelFrame = CGRectMake(0, 0, DEFAULT_LABEL_WIDTH, DEFAULT_LABEL_HEIGHT);
UILabel *loadingLabel = [[UILabel alloc] initWithFrame:labelFrame];
loadingLabel.text = NSLocalizedString(#"Close", nil);
loadingLabel.textColor = [UIColor whiteColor];
loadingLabel.backgroundColor = [UIColor clearColor];
loadingLabel.textAlignment = UITextAlignmentCenter;
loadingLabel.font = [UIFont boldSystemFontOfSize:[UIFont labelFontSize]];
loadingLabel.autoresizingMask =
UIViewAutoresizingFlexibleLeftMargin |
UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleTopMargin |
UIViewAutoresizingFlexibleBottomMargin;
// Background for Close button
CALayer *closeButtonBackground = [CALayer layer];
closeButtonBackground.opacity = 0.3;
closeButtonBackground.borderColor = [UIColor whiteColor].CGColor;
closeButtonBackground.borderWidth = 2.0;
closeButtonBackground.cornerRadius = 5.0;
closeButtonBackground.backgroundColor = [UIColor blackColor].CGColor;
// Finish setting up frame for Close button
labelFrame.origin.x = 0;
labelFrame.origin.y = 0;
loadingLabel.frame = labelFrame;
closeButtonBackground.frame = labelFrame;
CGRect viewRect = CGRectMake(loadingView.frame.size.width -150 ,loadingView.frame.size.height - 85,100,40);
self.closeButton = [[UIView alloc] initWithFrame:viewRect];
self.closeButton.userInteractionEnabled = YES;
self.userInteractionEnabled = NO;
[loadingView addSubview:self.closeButton];
[self.closeButton.layer addSublayer:closeButtonBackground];
[self.closeButton addSubview:loadingLabel];
// Set up the fade-in animation
CATransition *animation = [CATransition animation];
[animation setType:kCATransitionFade];
[[aSuperview layer] addAnimation:animation forKey:#"layerAnimation"];
//[loadingView createGestureRecognizer];
return loadingView;
}
- (void)removeView
{
UIView *aSuperview = [self superview];
[super removeFromSuperview];
// Set up the animation
CATransition *animation = [CATransition animation];
[animation setType:kCATransitionFade];
[[aSuperview layer] addAnimation:animation forKey:#"layerAnimation"];
}
- (void)drawRect:(CGRect)rect
{
rect.size.height -= 1;
rect.size.width -= 1;
const CGFloat RECT_PADDING = 0.0;
rect = CGRectInset(rect, RECT_PADDING, RECT_PADDING);
const CGFloat ROUND_RECT_CORNER_RADIUS = 0.0;
CGPathRef roundRectPath = NewPathWithRoundRect(rect, ROUND_RECT_CORNER_RADIUS);
CGContextRef context = UIGraphicsGetCurrentContext();
const CGFloat BACKGROUND_OPACITY = 0.85;
CGContextSetRGBFillColor(context, 0, 0, 0, BACKGROUND_OPACITY);
CGContextAddPath(context, roundRectPath);
CGContextFillPath(context);
const CGFloat STROKE_OPACITY = 0.25;
CGContextSetRGBStrokeColor(context, 1, 1, 1, STROKE_OPACITY);
CGContextAddPath(context, roundRectPath);
CGContextStrokePath(context);
CGPathRelease(roundRectPath);
}
- (void)handleSingleDoubleTap:(UITapGestureRecognizer *)sender {
NSLog(#"");
CGPoint tapPoint = [sender locationInView:sender.view];
CALayer* layerThatWasTapped = [self.layer hitTest:tapPoint];
CGPoint convertedPoint = [layerThatWasTapped convertPoint:layerThatWasTapped.position toLayer:self.closeButton.layer];
BOOL myBool = [self.closeButton.layer containsPoint:convertedPoint];
[UIView beginAnimations:nil context:NULL];
sender.view.center = tapPoint;
[UIView commitAnimations];
}
- (void) touchesEnded: (NSSet *) touches withEvent: (UIEvent *) event {
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView: self];
CGPoint convertedPoint = [self convertPoint:point toView:[self.closeButton superview]];
if (CGRectContainsPoint(self.closeButton.bounds, convertedPoint)) {
NSLog (#"YAY!");
}
} // touchesEnded
Solved this with NSNotifications. Something like this... its a little static... should be more dynamic.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(eventHandler:)
name:#"SomeButtonClicked"
object:nil ];
-(void)eventHandler: (NSNotification *) notification
{
NSString *buttonWhichWasClicked = [[notification userInfo] objectForKey:#"buttonName"];
NSLog(#" %#", buttonWhichWasClicked);
if ([buttonWhichWasClicked isEqualToString:#"close"]){
[self removeView];
}
//Tell other buttons to dim/remove themselves as a new one was selected
}
- (void)removeView
{
//code to remove view
}

Making a circular NSSlide look and behave like in GarageBand

I am new to drawing with Cocoa, and I am making some software which will have sliders similar to these found in GarageBand:
GB Sliders http://img33.imageshack.us/img33/2668/schermafbeelding2010061r.png
These look beautiful and can be controld by moving the mouse up and down.
Can you help me with customizing NSSliders by subclassing them, so I can make them look and behave exactly as in GarageBand? Thanks.
I have one image for the knob which should be rotated as they do not need to be in 3D .
The simplest way is to create a NSView subclass that handles both the mouse management and the drawing.
There is a sample code that can help you to start named "TLayer". It is part of the Examples of the XCode 3.1.4. It contains a circular custom view that controls the offset and the radius of the shadow drawn for layers. It is easy to understand and easy to extend.
Note: as it does not seems to be available on the Apple website, so I have pasted the sources below.
ShadowOffsetView.h
#import <AppKit/AppKit.h>
extern NSString *ShadowOffsetChanged;
#interface ShadowOffsetView : NSView
{
CGSize _offset;
float _scale;
}
- (float)scale;
- (void)setScale:(float)scale;
- (CGSize)offset;
- (void)setOffset:(CGSize)offset;
#end
ShadowOffsetView.m
#import "ShadowOffsetView.h"
NSString *ShadowOffsetChanged = #"ShadowOffsetChanged";
#interface ShadowOffsetView (Internal)
- (NSCell *)cell;
#end
#implementation ShadowOffsetView
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self == nil)
return nil;
_offset = CGSizeZero;
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (float)scale
{
return _scale;
}
- (void)setScale:(float)scale
{
_scale = scale;
}
- (CGSize)offset
{
return CGSizeMake(_offset.width * _scale, _offset.height * _scale);
}
- (void)setOffset:(CGSize)offset
{
offset = CGSizeMake(offset.width / _scale, offset.height / _scale);
if (!CGSizeEqualToSize(_offset, offset)) {
_offset = offset;
[self setNeedsDisplay:YES];
}
}
- (BOOL)isOpaque
{
return NO;
}
- (void)setOffsetFromPoint:(NSPoint)point
{
float radius;
CGSize offset;
NSRect bounds;
bounds = [self bounds];
offset.width = (point.x - NSMidX(bounds)) / (NSWidth(bounds) / 2);
offset.height = (point.y - NSMidY(bounds)) / (NSHeight(bounds) / 2);
radius = sqrt(offset.width * offset.width + offset.height * offset.height);
if (radius > 1) {
offset.width /= radius;
offset.height /= radius;
}
if (!CGSizeEqualToSize(_offset, offset)) {
_offset = offset;
[self setNeedsDisplay:YES];
[(NSNotificationCenter *)[NSNotificationCenter defaultCenter]
postNotificationName:ShadowOffsetChanged object:self];
}
}
- (void)mouseDown:(NSEvent *)event
{
NSPoint point;
point = [self convertPoint:[event locationInWindow] fromView:nil];
[self setOffsetFromPoint:point];
}
- (void)mouseDragged:(NSEvent *)event
{
NSPoint point;
point = [self convertPoint:[event locationInWindow] fromView:nil];
[self setOffsetFromPoint:point];
}
- (void)drawRect:(NSRect)rect
{
NSRect bounds;
CGContextRef context;
float x, y, w, h, r;
bounds = [self bounds];
x = NSMinX(bounds);
y = NSMinY(bounds);
w = NSWidth(bounds);
h = NSHeight(bounds);
r = MIN(w / 2, h / 2);
context = [[NSGraphicsContext currentContext] graphicsPort];
CGContextTranslateCTM(context, x + w/2, y + h/2);
CGContextAddArc(context, 0, 0, r, 0, 2*M_PI, true);
CGContextClip(context);
CGContextSetGrayFillColor(context, 0.910, 1);
CGContextFillRect(context, CGRectMake(-w/2, -h/2, w, h));
CGContextAddArc(context, 0, 0, r, 0, 2*M_PI, true);
CGContextSetGrayStrokeColor(context, 0.616, 1);
CGContextStrokePath(context);
CGContextAddArc(context, 0, -2, r, 0, 2*M_PI, true);
CGContextSetGrayStrokeColor(context, 0.784, 1);
CGContextStrokePath(context);
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, r * _offset.width, r * _offset.height);
CGContextSetLineWidth(context, 2);
CGContextSetGrayStrokeColor(context, 0.33, 1);
CGContextStrokePath(context);
}
#end
Well, for the actual drawing you'd either have to have images for each rotation angle of the knob (easier to implement) and then just draw the proper one.
(While for a real realistic 3d look—even if possible—programmatic drawing wouldn't be worth its time, I guess.)
Or draw the knob by code. This article should give you an idea I think:
http://katidev.com/blog/2008/03/07/how-to-create-a-custom-control-with-nsview/
(For both, the mouse event handling and basic NSBezerPath drawing of circular and rotating knob-like elements)