CAShapeLayer Shadow with UIBezierPath - objective-c

This question continues from a previous answer.
I have the following CAShapeLayer:
- (CAShapeLayer *)gaugeCircleLayer {
if (_gaugeCircleLayer == nil) {
_gaugeCircleLayer = [CAShapeLayer layer];
_gaugeCircleLayer.lineWidth = self.gaugeWidth;
_gaugeCircleLayer.fillColor = [UIColor clearColor].CGColor;
_gaugeCircleLayer.strokeColor = self.gaugeTintColor.CGColor;
_gaugeCircleLayer.strokeStart = 0.0f;
_gaugeCircleLayer.strokeEnd = self.value;
_gaugeCircleLayer.lineCap = kCALineCapRound;
_gaugeCircleLayer.path = [self insideCirclePath].CGPath;
CAShapeLayer *cap = [CAShapeLayer layer];
cap.shadowColor = [UIColor blackColor].CGColor;
cap.shadowRadius = 8.0;
cap.shadowOpacity = 0.9;
cap.shadowOffset = CGSizeMake(0, 0);
cap.fillColor = [UIColor grayColor].CGColor;
[_gaugeCircleLayer addSublayer:cap];
}
return _gaugeCircleLayer;
}
Then I have the following UIBezierPath:
- (UIBezierPath *)insideCirclePath {
CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:arcCenter
radius:CGRectGetWidth(self.bounds) / 2.0f
startAngle:(3.0f * M_PI_2)
endAngle:(3.0f * M_PI_2) + (2.0f * M_PI)
clockwise:YES];
return path;
}
This produces something like the following:
What I am trying to produce with the cap sublayer is the drop shadow at the end and I'd also be interested to know how to get a GradientLayer working similar to the image below:
The problem is that the sublayer is not appearing anywhere and I'm not quite sure why. I'm also not 100% sure on whether or not this is the best way to produce the desired effect.
UPDATE:
The following bit of code creates a cap, though I'm not quite sure how to add it to my UIBezierPath properly:
let cap = CAShapeLayer()
cap.shadowColor = UIColor.blackColor().CGColor
cap.shadowRadius = 8.0
cap.shadowOpacity = 0.9
cap.shadowOffset = CGSize(width: 0, height: 0)
cap.path = UIBezierPath(ovalInRect: CGRectMake(0, 40, 20, 20)).CGPath
cap.fillColor = UIColor.grayColor().CGColor
layer.addSublayer(cap)

I don't know if this will be useful to you, since it doesn't use the CHCircleGaugeView. I was working on several projects related to this question, so I mashed them together and made some changes to produce a progress view that has a color gradient background with a tip that overlaps the end at 100%. I haven't gotten to the point where I make the rounded tip disappear at 0%, but I'll get there eventually. Here are a couple of views of it at 2 different progress levels,
The view is created with a polar gradient drawn in drawRect, masked by an annulus. The rounded tip is a separate layer that's a half circle on the end of a line connected to the center of the circle that's revolved around its center with a transform based on the progress level. Here's the code,
#implementation AnnulusProgressView{ // subclass of UIView
int slices;
CGFloat circleRadius;
CAShapeLayer *maskLayer;
CGFloat segmentAngle;
CGFloat startAngle;
CAShapeLayer *tipView;
NSMutableArray *colors;
int sign;
}
-(instancetype)initWithFrame:(CGRect)frame wantsBackgroundRing:(BOOL)wantsBackground backgroundRingColor:(UIColor *)ringColor {
if (self = [super initWithFrame:frame]) {
slices = 360;
_ringThickness = 12;
circleRadius = self.bounds.size.width/2;
_startColor = [UIColor colorWithHue:0.24 saturation:1 brightness:0.8 alpha:1];
_endColor = [UIColor colorWithHue:0.03 saturation:1 brightness:1 alpha:1];
[self setupColorArray];
_backgroundRing = wantsBackground? [self createBackgroundRingWithColor:ringColor] : nil;
self.layer.mask = [self createAnnulusMask];
}
return self;
}
-(void)setStartColor:(UIColor *)startColor {
_startColor = startColor;
[self setupColorArray];
}
-(void)setEndColor:(UIColor *)endColor {
_endColor = endColor;
[self setupColorArray];
}
-(void)setupColorArray {
colors = [NSMutableArray new];
CGFloat startHue, startSaturation, startBrightness, startAlpha, endHue, endSaturation, endBrightness, endAlpha;
[self.startColor getHue:&startHue saturation:&startSaturation brightness:&startBrightness alpha:&startAlpha];
[self.endColor getHue:&endHue saturation:&endSaturation brightness:&endBrightness alpha:&endAlpha];
for(int i=0;i<slices;i++){
CGFloat hue = startHue + (endHue - startHue)*i/slices;
CGFloat brightness = startBrightness + (endBrightness - startBrightness)*i/slices;
CGFloat saturation = startSaturation + (endSaturation - startSaturation)*i/slices;
CGFloat alpha = startAlpha + (endAlpha - startAlpha)*i/slices;
UIColor *color = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
[colors addObject:color];
}
self.progress = _progress;
}
-(UIView *)createBackgroundRingWithColor:(UIColor *) color {
UIView *bgRing = [[UIView alloc] initWithFrame:self.frame];
bgRing.backgroundColor = color;
bgRing.layer.mask = [self createAnnulusMask];
[(CAShapeLayer *)bgRing.layer.mask setStrokeEnd:startAngle + 2*M_PI ];
return bgRing;
}
-(void)didMoveToSuperview {
if (self.backgroundRing) [self.superview insertSubview:self.backgroundRing belowSubview:self];
tipView = [self tipView];
[self.superview.layer addSublayer:tipView];
}
-(CAShapeLayer *)tipView {
CAShapeLayer *tip = [CAShapeLayer layer];
tip.frame = self.frame;
tip.fillColor = [UIColor redColor].CGColor;
UIBezierPath *shape = [UIBezierPath bezierPath];
CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
[shape moveToPoint:center];
CGPoint bottomPoint = CGPointMake(center.x, center.y + circleRadius - self.ringThickness*2);
CGFloat tipCenterY = bottomPoint.y + self.ringThickness - 1;
[shape addLineToPoint: bottomPoint];
[shape addLineToPoint:CGPointMake(bottomPoint.x+2, bottomPoint.y)];
double fractionAlongTangent = self.ringThickness;
[shape addCurveToPoint:CGPointMake(center.x, center.y + circleRadius) controlPoint1:CGPointMake(center.x - self.ringThickness*1.5, tipCenterY - fractionAlongTangent) controlPoint2:CGPointMake(center.x - self.ringThickness*1.5, tipCenterY + fractionAlongTangent)];
[shape closePath];
tip.path = shape.CGPath;
tip.shadowColor = [UIColor darkGrayColor].CGColor;
tip.shadowOpacity = 0.8;
tip.shadowOffset = CGSizeMake(-6, 0);
tip.shadowRadius = 2;
return tip;
}
- (void)setProgress:(CGFloat)progress{
sign = (progress >= _progress)? 1 : -1;
[self animateProgressTo:#(progress)];
}
-(void)animateProgressTo:(NSNumber *) newValueNumber{
float newValue = newValueNumber.floatValue;
_progress = (_progress + (sign * 0.1) > 1)? 1 : _progress + (sign * 0.1);
if ((_progress > newValue && sign == 1) || (_progress < newValue && sign == -1)) {
_progress = newValue;
}
maskLayer.strokeEnd = _progress;
tipView.transform = CATransform3DMakeRotation(-(1 - _progress + 0.002) * M_PI*2, 0, 0, 1); //the 0.002 closes a small gap between the tip and the annulus strokeEnd
int i = (int)(_progress*(slices - 1));
tipView.fillColor = ((UIColor *)colors[i]).CGColor;
if (sign == 1) {
if (_progress < newValue) {
[self performSelector:#selector(animateProgressTo:) withObject:#(newValue) afterDelay:0.05];
}
}else{
if (_progress > newValue) {
[self performSelector:#selector(animateProgressTo:) withObject:#(newValue) afterDelay:0.05];
}
}
NSLog(#"%f",_progress);
}
- (CAShapeLayer *)createAnnulusMask {
maskLayer = [CAShapeLayer layer];
maskLayer.frame = self.bounds;
segmentAngle = 2*M_PI/(slices);
startAngle = M_PI_2;
CGFloat endAngle = startAngle + 2*M_PI;
maskLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds)) radius:circleRadius - self.ringThickness startAngle:startAngle endAngle:endAngle clockwise:YES].CGPath;
maskLayer.fillColor = [UIColor clearColor].CGColor;
maskLayer.strokeColor = [UIColor blackColor].CGColor;
maskLayer.lineWidth = self.ringThickness * 2;
maskLayer.strokeEnd = self.progress;
return maskLayer;
}
-(void)drawRect:(CGRect)rect{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetAllowsAntialiasing(ctx, NO);
CGPoint center = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
for(int i=0;i<slices;i++){
CGContextSaveGState(ctx);
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:center];
[path addArcWithCenter:center radius:circleRadius startAngle:startAngle endAngle:startAngle+segmentAngle clockwise:YES];
[path addClip];
[colors[i] setFill];
[path fill];
CGContextRestoreGState(ctx);
startAngle += segmentAngle;
}
}

This should resolve the problem.
Only remaining issue is the animation, whereby the cap is not animated.
The trick was to add the cap to the end of the gauge, and update it when the value of the gauge changed. To calculate the location, a little math magic was used. It needs to be under the gauge, so the cap is added in the trackCircleLayer
//
// CHCircleGaugeView.m
//
// Copyright (c) 2014 ChaiOne <http://www.chaione.com/>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "CHCircleGaugeView.h"
#import "CHCircleGaugeViewDebugMacros.h"
#import <CoreText/CoreText.h>
#import <QuartzCore/QuartzCore.h>
static CGFloat const CHKeyAnimationDuration = 0.5f;
static CGFloat const CHKeyDefaultValue = 0.0f;
static CGFloat const CHKeyDefaultFontSize = 32.0f;
static CGFloat const CHKeyDefaultTrackWidth = 0.5f;
static CGFloat const CHKeyDefaultGaugeWidth = 2.0f;
static NSString * const CHKeyDefaultNAText = #"n/a";
static NSString * const CHKeyDefaultNoAnswersText = #"%";
#define CHKeyDefaultTrackTintColor [UIColor blackColor]
#define CHKeyDefaultGaugeTintColor [UIColor blackColor]
#define CHKeyDefaultTextColor [UIColor blackColor]
#interface CHCircleGaugeView ()
#property (nonatomic, strong) CAShapeLayer *trackCircleLayer;
#property (nonatomic, strong) CAShapeLayer *gaugeCircleLayer;
// ADDED
#property (nonatomic, strong) CAShapeLayer *capLayer;
// END ADDED
#property (nonatomic, strong) UILabel *valueTextLabel;
#end
#implementation CHCircleGaugeView
#pragma mark - View Initialization
- (instancetype)init {
return [self initWithFrame:CGRectZero];
}
- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self initSetup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
[self initSetup];
}
return self;
}
- (void)initSetup {
_state = CHCircleGaugeViewStateNA;
_value = CHKeyDefaultValue;
_trackTintColor = CHKeyDefaultTrackTintColor;
_gaugeTintColor = CHKeyDefaultGaugeTintColor;
_textColor = CHKeyDefaultTextColor;
_font = [UIFont systemFontOfSize:CHKeyDefaultFontSize];
_trackWidth = CHKeyDefaultTrackWidth;
_gaugeWidth = CHKeyDefaultGaugeWidth;
_notApplicableString = CHKeyDefaultNAText;
_noDataString = CHKeyDefaultNoAnswersText;
[self createGauge];
}
- (void)createGauge {
[self.layer addSublayer:self.trackCircleLayer];
[self.layer addSublayer:self.gaugeCircleLayer];
[self addSubview:self.valueTextLabel];
[self setupConstraints];
}
- (void)setupConstraints {
NSDictionary *viewDictionary = #{#"valueText" : self.valueTextLabel};
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"V:|[valueText]|" options:0 metrics:nil views:viewDictionary]];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:|[valueText]|" options:0 metrics:nil views:viewDictionary]];
}
#pragma mark - Property Setters
- (void)setState:(CHCircleGaugeViewState)state {
if (_state != state) {
_state = state;
switch (state) {
case CHCircleGaugeViewStateNA: {
[self updateGaugeWithValue:0 animated:NO];
break;
}
case CHCircleGaugeViewStatePercentSign: {
[self updateGaugeWithValue:0 animated:NO];
break;
}
case CHCircleGaugeViewStateScore: {
[self updateGaugeWithValue:self.value animated:NO];
break;
}
default: {
ALog(#"Missing gauge state.");
break;
}
}
}
}
- (void)setValue:(CGFloat)value {
[self setValue:value animated:NO];
}
- (void)setValue:(CGFloat)value animated:(BOOL)animated {
self.state = CHCircleGaugeViewStateScore;
if (value != _value) {
[self willChangeValueForKey:NSStringFromSelector(#selector(value))];
value = MIN(1.0f, MAX(0.0f, value));
[self updateGaugeWithValue:value animated:animated];
_value = value;
[self didChangeValueForKey:NSStringFromSelector(#selector(value))];
}
}
- (void)setUnitsString:(NSString *)unitsString {
if ([_unitsString isEqualToString:unitsString] == NO) {
_unitsString = [unitsString copy];
self.valueTextLabel.attributedText = [self formattedStringForValue:self.value];
}
}
- (void)updateGaugeWithValue:(CGFloat)value animated:(BOOL)animated {
self.valueTextLabel.attributedText = [self formattedStringForValue:value];
BOOL previousDisableActionsValue = [CATransaction disableActions];
[CATransaction setDisableActions:YES];
self.gaugeCircleLayer.strokeEnd = value;
// ADDED
_capLayer.path = [self capPathForValue:value].CGPath;
// END ADDED
if (animated) {
self.gaugeCircleLayer.strokeEnd = value;
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = CHKeyAnimationDuration;
pathAnimation.fromValue = [NSNumber numberWithFloat:self.value];
pathAnimation.toValue = [NSNumber numberWithFloat:value];
pathAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
[self.gaugeCircleLayer addAnimation:pathAnimation forKey:#"strokeEndAnimation"];
}
[CATransaction setDisableActions:previousDisableActionsValue];
}
- (void)setTrackTintColor:(UIColor *)trackTintColor {
if (_trackTintColor != trackTintColor) {
_trackTintColor = trackTintColor;
self.trackCircleLayer.strokeColor = trackTintColor.CGColor;
}
}
- (void)setGaugeTintColor:(UIColor *)gaugeTintColor {
if (_gaugeTintColor != gaugeTintColor) {
_gaugeTintColor = gaugeTintColor;
self.gaugeCircleLayer.strokeColor = gaugeTintColor.CGColor;
// ADDED
self.capLayer.fillColor = gaugeTintColor.CGColor;
// END ADDED
}
}
- (void)setTrackWidth:(CGFloat)trackWidth {
if (_trackWidth != trackWidth) {
_trackWidth = trackWidth;
self.trackCircleLayer.lineWidth = trackWidth;
[self.layer layoutSublayers];
}
}
- (void)setGaugeWidth:(CGFloat)gaugeWidth {
if (_gaugeWidth != gaugeWidth) {
_gaugeWidth = gaugeWidth;
self.gaugeCircleLayer.lineWidth = gaugeWidth;
[self.layer layoutSublayers];
}
}
- (void)setTextColor:(UIColor *)textColor {
if (_textColor != textColor) {
_textColor = textColor;
self.valueTextLabel.textColor = textColor;
}
}
- (void)setFont:(UIFont *)font {
if (_font != font) {
_font = font;
self.valueTextLabel.font = font;
}
}
- (void)setGaugeStyle:(CHCircleGaugeStyle)gaugeStyle {
if (_gaugeStyle != gaugeStyle) {
_gaugeStyle = gaugeStyle;
[self.layer layoutSublayers];
}
}
#pragma mark - Circle Shapes
- (CAShapeLayer *)trackCircleLayer {
if (_trackCircleLayer == nil) {
_trackCircleLayer = [CAShapeLayer layer];
_trackCircleLayer.lineWidth = self.trackWidth;
_trackCircleLayer.fillColor = [UIColor clearColor].CGColor;
_trackCircleLayer.strokeColor = self.trackTintColor.CGColor;
_trackCircleLayer.path = [self insideCirclePath].CGPath;
// ADDED
_capLayer = [CAShapeLayer layer];
_capLayer.shadowColor = [UIColor blackColor].CGColor;
_capLayer.shadowRadius = 8.0;
_capLayer.shadowOpacity = 0.9;
_capLayer.shadowOffset = CGSizeMake(0, 0);
_capLayer.fillColor = self.gaugeTintColor.CGColor;
_capLayer.path = [self capPathForValue:self.value].CGPath;
[_trackCircleLayer addSublayer:_capLayer];
// END ADDED
}
return _trackCircleLayer;
}
- (CAShapeLayer *)gaugeCircleLayer {
if (_gaugeCircleLayer == nil) {
_gaugeCircleLayer = [CAShapeLayer layer];
_gaugeCircleLayer.lineWidth = self.gaugeWidth;
_gaugeCircleLayer.fillColor = [UIColor clearColor].CGColor;
_gaugeCircleLayer.strokeColor = self.gaugeTintColor.CGColor;
_gaugeCircleLayer.strokeStart = 0.0f;
_gaugeCircleLayer.strokeEnd = self.value;
_gaugeCircleLayer.path = [self circlPathForCurrentGaugeStyle].CGPath;
}
return _gaugeCircleLayer;
}
// ADDED
- (UIBezierPath *)capPathForValue:(float)value {
CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
CGFloat radius = CGRectGetWidth(self.bounds) / 2.0f;
float angle = value * 360.0;
float x = radius * sin(angle*M_PI/180.0);
float y = radius * cos(angle*M_PI/180.0);
CGPoint capArcCenter = CGPointMake(arcCenter.x + x, arcCenter.y - y);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:capArcCenter
radius:self.gaugeWidth*_capLayer.shadowRadius / 2.0f
startAngle:(3.0f * M_PI_2)
endAngle:(3.0f * M_PI_2) + (2.0f * M_PI)
clockwise:YES];
return path;
}
// END ADDED
- (UIBezierPath *)circlPathForCurrentGaugeStyle {
switch (self.gaugeStyle) {
case CHCircleGaugeStyleInside: {
return [self insideCirclePath];
}
case CHCircleGaugeStyleOutside: {
return [self outsideCirclePath];
}
default: {
return nil;
}
}
}
- (UIBezierPath *)insideCirclePath {
CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:arcCenter
radius:CGRectGetWidth(self.bounds) / 2.0f
startAngle:(3.0f * M_PI_2)
endAngle:(3.0f * M_PI_2) + (2.0f * M_PI)
clockwise:YES];
return path;
}
- (UIBezierPath *)outsideCirclePath {
CGPoint arcCenter = CGPointMake(CGRectGetMidX(self.bounds), CGRectGetMidY(self.bounds));
CGFloat radius = (CGRectGetWidth(self.bounds) / 2.0f) + (self.trackWidth / 2.0f) + (self.gaugeWidth / 2.0f);
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:arcCenter
radius:radius
startAngle:(3.0f * M_PI_2)
endAngle:(3.0f * M_PI_2) + (2.0f * M_PI)
clockwise:YES];
return path;
}
#pragma mark - Text Label
- (UILabel *)valueTextLabel {
if (_valueTextLabel == nil) {
_valueTextLabel = [[UILabel alloc] init];
[_valueTextLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
_valueTextLabel.textAlignment = NSTextAlignmentCenter;
_valueTextLabel.attributedText = [self formattedStringForValue:self.value];
}
return _valueTextLabel;
}
- (NSAttributedString *)formattedStringForValue:(CGFloat)value {
NSAttributedString *valueString;
NSDictionary *stringAttributes = #{
NSForegroundColorAttributeName : self.textColor,
NSFontAttributeName : self.font
};
switch (self.state) {
case CHCircleGaugeViewStateNA: {
valueString = [[NSAttributedString alloc] initWithString:self.notApplicableString attributes:stringAttributes];
break;
}
case CHCircleGaugeViewStatePercentSign: {
valueString = [[NSAttributedString alloc] initWithString:self.noDataString attributes:stringAttributes];
break;
}
case CHCircleGaugeViewStateScore: {
NSString *suffix = self.unitsString ? self.unitsString : #"";
valueString = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:#"%.0f %#", value * 100.0f, suffix]
attributes:stringAttributes];
break;
}
default: {
ALog(#"Missing gauge state.");
break;
}
}
return valueString;
}
#pragma mark - KVO
// Handling KVO notifications for the value property, since
// we're proxying with the setValue:animated: method.
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)key {
if ([key isEqualToString:NSStringFromSelector(#selector(value))]) {
return NO;
} else {
return [super automaticallyNotifiesObserversForKey:key];
}
}
#pragma mark - CALayerDelegate
- (void)layoutSublayersOfLayer:(CALayer *)layer {
[super layoutSublayersOfLayer:layer];
if (layer == self.layer) {
self.trackCircleLayer.path = [self insideCirclePath].CGPath;
self.gaugeCircleLayer.path = [self circlPathForCurrentGaugeStyle].CGPath;
}
}
#end

Related

Couldn't resolve variable issue Objective-C

I'm not much of an Objective-C guy I primarily use swift and I need some help from this error
Variable 'indexOfLargestGap' may be uninitialized when used here
and
Variable 'indexOfSmallestGap' may be uninitialized when used here
I have imported the code from Github and created a bridging header and fixed a few errors but I don't know how to fix this one.
The original file from Github https://github.com/jberlana/JBCroppableView
#import "JBCroppableImageView.h"
#import "JBCroppableLayer.h"
#implementation JBCroppableImageView{
JBCroppableLayer *_pointsView;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
self.userInteractionEnabled = YES;
_pointsView = [[JBCroppableLayer alloc] initWithImageView:self];
[_pointsView addPoints:4];
[self addSubview:_pointsView];
UIPanGestureRecognizer *singlePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(singlePan:)];
singlePan.maximumNumberOfTouches = 1;
[self addGestureRecognizer:singlePan];
UIPanGestureRecognizer *doublePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(doublePan:)];
doublePan.minimumNumberOfTouches = 2;
[self addGestureRecognizer:doublePan];
}
return self;
}
-(void)singlePan:(UIPanGestureRecognizer *)gesture{
CGPoint posInStretch = [gesture locationInView:_pointsView];
if(gesture.state==UIGestureRecognizerStateBegan){
[_pointsView findPointAtLocation:posInStretch];
}
if(gesture.state==UIGestureRecognizerStateEnded){
_pointsView.activePoint.backgroundColor = _pointsView.pointColor;
_pointsView.activePoint = nil;
}
[_pointsView moveActivePointToLocation:posInStretch];
// CGPoint translation = [gesture translationInView:self.imageView];
// [gesture setTranslation:CGPointZero inView:self.imageView];
}
-(void)doublePan:(UIPanGestureRecognizer *)gesture{
NSLog(#"double pan");
CGPoint translation = [gesture translationInView:self];
CGPoint newCenter = CGPointMake(self.center.x+translation.x, self.center.y+translation.y);
[self setCenter:newCenter];
[gesture setTranslation:CGPointZero inView:self];
}
-(void)crop{
[_pointsView maskImageView:self];
[_pointsView removeFromSuperview];
}
-(void)reverseCrop{
self.layer.mask = nil;
[self addSubview:_pointsView];
}
-(UIImage *)getCroppedImage{
return [_pointsView getCroppedImageForView:self withTransparentBorders:NO];
}
-(UIImage *)getCroppedImageWithTransparentBorders:(BOOL)transparent{
return [_pointsView getCroppedImageForView:self withTransparentBorders:transparent];
}
- (void)addPoint{
self.layer.mask = nil;
NSMutableArray *oldPoints = [_pointsView.getPoints mutableCopy];
// CGPoint new = CGPointMake((first.x+last.x)/2.0f, (first.y+last.y)/2.0f);
NSInteger indexOfLargestGap; //points to here for first warning
CGFloat largestGap = 0;
for(int i=0; i< oldPoints.count-1; i++){
CGPoint first = [[oldPoints objectAtIndex:i] CGPointValue];
CGPoint last = [[oldPoints objectAtIndex:i+1] CGPointValue];
CGFloat distance = [self distanceBetween:first And:last];
if(distance>largestGap){
indexOfLargestGap = i+1;
largestGap = distance;
}
}
CGPoint veryFirst = [[oldPoints firstObject] CGPointValue];
CGPoint veryLast = [[oldPoints lastObject] CGPointValue];
CGPoint new;
if([self distanceBetween:veryFirst And:veryLast]>largestGap){
indexOfLargestGap = oldPoints.count;
new = CGPointMake((veryFirst.x+veryLast.x)/2.0f, (veryFirst.y+veryLast.y)/2.0f);
} else {
CGPoint first = [[oldPoints objectAtIndex:indexOfLargestGap-1] CGPointValue];//Variable 'indexOfLargestGap' may be uninitialized when used here
CGPoint last = [[oldPoints objectAtIndex:indexOfLargestGap] CGPointValue];
new = CGPointMake((first.x+last.x)/2.0f, (first.y+last.y)/2.0f);
}
[oldPoints insertObject:[NSValue valueWithCGPoint:new] atIndex:indexOfLargestGap];
[_pointsView removeFromSuperview];
_pointsView = [[JBCroppableLayer alloc] initWithImageView:self];
[_pointsView addPointsAt:oldPoints];
[self addSubview:_pointsView];
}
- (void)removePoint{
self.layer.mask = nil;
NSMutableArray *oldPoints = [_pointsView.getPoints mutableCopy];
if(oldPoints.count==3) return;
NSInteger indexOfSmallestGap;// points to here for second warning
CGFloat smallestGap = INFINITY;
for(int i=0; i< oldPoints.count; i++){
int firstIndex = i-1;
int lastIndex = i +1;
if(firstIndex<0){
firstIndex = (int)oldPoints.count-1+firstIndex;
} else if(firstIndex>=oldPoints.count){
firstIndex = firstIndex-(int)oldPoints.count;
}
if(lastIndex<0){
lastIndex = (int)oldPoints.count-1+lastIndex;
} else if(lastIndex>=oldPoints.count){
lastIndex = lastIndex-(int)oldPoints.count;
}
CGPoint first = [[oldPoints objectAtIndex:firstIndex] CGPointValue];
CGPoint mid = [[oldPoints objectAtIndex:i] CGPointValue];
CGPoint last = [[oldPoints objectAtIndex:lastIndex] CGPointValue];
CGFloat distance = [self distanceFrom:first to:last throuh:mid];
if(distance<smallestGap){
indexOfSmallestGap = i;
smallestGap = distance;
}
}
[oldPoints removeObjectAtIndex:indexOfSmallestGap]; //Variable 'indexOfSmallestGap' may be uninitialized when used here
[_pointsView removeFromSuperview];
_pointsView = [[JBCroppableLayer alloc] initWithImageView:self];
[_pointsView addPointsAt:[NSArray arrayWithArray:oldPoints]];
[self addSubview:_pointsView];
}
-(CGFloat)distanceBetween:(CGPoint)first And:(CGPoint)last{
CGFloat xDist = (last.x - first.x);
if(xDist<0) xDist=xDist*-1;
CGFloat yDist = (last.y - first.y);
if(yDist<0) yDist=yDist*-1;
return sqrt((xDist * xDist) + (yDist * yDist));
}
-(CGFloat)distanceFrom:(CGPoint)first to:(CGPoint)last throuh:(CGPoint)middle{
CGFloat firstToMid = [self distanceBetween:first And:middle];
CGFloat lastToMid = [self distanceBetween:middle And:last];
return firstToMid + lastToMid;
}
-(void)setFrame:(CGRect)frame{
[super setFrame:frame];
[_pointsView setFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
[_pointsView setNeedsDisplay];
}
#end
And I'm getting this from the terminal
index 0 beyond bounds for empty array

How to receive mouseDown messages in a NSTableViewCell?

I am trying to make a table view cell that shows ratings for songs in a playlist. I have successfully created the cell so that it shows the current number of stars, and also an indication of how a new setting will be when you hover your mouse cursor over a cell to give a new rating.
The problem is that while mouseEnter, mouseExit and mouseMove works like a charm, I get no messages for mouseDown, which is required to actually change the value of the cell.
I have searched all over the Internet, but I can't find any solution to how to solve this problem anywhere. I have spent so many hours trying to sort this. I hope anyone have any answer or hint what I can do. Thank you.
The full code for the current implementation is as follows:
#import "FavouriteCellView.h"
#implementation FavouriteCellView {
NSTrackingArea *_trackingArea;
int _starsRated; //The current rating value
BOOL _hovering; //YES if the mouse is currently hovering over this cell
int _starsHovering; //The number of stars hovering, if the mouse is hovering over this cell
}
- (void)awakeFromNib {
[super awakeFromNib];
_starsRated = 1;
_hovering = NO;
_starsHovering = 0;
[self createTrackingArea];
}
- (void)createTrackingArea
{
_trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited |NSTrackingActiveInActiveApp | NSTrackingMouseMoved owner:self userInfo:nil];
[self addTrackingArea:_trackingArea];
}
- (void)updateTrackingAreas{
[self removeTrackingArea:_trackingArea];
_trackingArea = nil;
[self createTrackingArea];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// CGFloat middleX = [self bounds].size.width / 2.0f;
CGFloat middleY = [self bounds].size.height / 2.0f;
CGFloat starDivs = [self bounds].size.width / 5.0f;;
NSColor *starSelectedColor = [NSColor colorWithDeviceRed:0.8f green:0.0f blue:0.4f alpha:1.0f];
NSColor *starUnselectedColor = [NSColor colorWithDeviceRed:0.5f green:0.5f blue:0.5f alpha:1.0f];
NSColor *starHoverColor = [NSColor colorWithDeviceRed:1.0f green:0.843f blue:0.0f alpha:1.0f];
NSColor *starHoverColorSelected = [NSColor colorWithDeviceRed:0.9f green:0.843f blue:0.6f alpha:1.0f];
for (int i = 0; i < 5; i++) {
NSColor *useColor = [NSColor redColor];
if (_hovering && (i <= _starsHovering)) {
if (i <= _starsRated) {
useColor = starHoverColorSelected;
} else {
useColor = starHoverColor;
}
} else if (i <= _starsRated) {
useColor = starSelectedColor;
} else {
useColor = starUnselectedColor;
}
[self star:NSMakePoint((starDivs / 2.0f) + starDivs * i, middleY) color:useColor];
}
}
-(void)star:(NSPoint)center color:(NSColor *)color {
[color set];
CGFloat t = (2.0f * M_PI) / 10.0f;
NSBezierPath *path = [[NSBezierPath alloc] init];
CGFloat radii1 = 12.0f;
CGFloat radii2 = 4.0f;
CGFloat rot = M_PI / 2.0f;
BOOL first = YES;
for (int i = 0; i < 10; i++) {
CGFloat pointX = cos(t * i + rot) * radii1 + center.x;
CGFloat pointY = sin(t * i + rot) * radii1 + center.y;
CGFloat tempRadii = radii1;
radii1 = radii2;
radii2 = tempRadii;
if (first) {
first = NO;
[path moveToPoint:NSMakePoint(pointX, pointY)];
}
else {
[path lineToPoint:NSMakePoint(pointX, pointY)];
}
}
[path closePath];
[path fill];
/*
[[NSColor blackColor] set];
[path setLineWidth:0.25f];
[path stroke];
*/
}
-(NSView *)hitTest:(NSPoint)aPoint {
//THIS GETS CALLED
return self;
}
-(BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event {
printf("$"); //DOES NOT GET CALLED
return YES;
}
-(BOOL)acceptsFirstResponder {
printf("!"); //DOES NOT GET CALLED
return YES;
}
-(BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
printf("8"); //DOES NOT GET CALLED
return YES;
}
-(void)mouseDown:(NSEvent *)theEvent {
printf("o"); //DOES NOT GET CALLED
_starsRated = _starsHovering;
}
-(void)mouseUp:(NSEvent *)theEvent {
printf("O"); //DOES NOT GET CALLED
}
-(void)mouseEntered:(NSEvent *)theEvent {
//DOES GET CALLED
_hovering = YES;
[self setNeedsDisplay:YES];
}
-(void)mouseExited:(NSEvent *)theEvent {
//DOES GET CALLED
_hovering = NO;
[self setNeedsDisplay:YES];
}
-(void)mouseMoved:(NSEvent *)theEvent {
//DOES GET CALLED
NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];
mouseLocation = [self convertPoint: mouseLocation
fromView: nil];
int newStarsHoveringValue = mouseLocation.x / ([self bounds].size.width / 5.0f);
if (newStarsHoveringValue != _starsHovering) {
_starsHovering = newStarsHoveringValue;
[self setNeedsDisplay:YES];
}
}
#end
It was a bit fiddly, but I managed to create a solution that works. I subclassed NSTableView, then overrode mouseDown with the following code:
-(void)mouseDown:(NSEvent *)theEvent {
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
if (clickedRow != -1) {
NSInteger clickedColumn = [self columnAtPoint:localLocation];
if (clickedColumn != -1) {
if (clickedColumn == 3) {
FavouriteCellView *fv = [self viewAtColumn:clickedColumn row:clickedRow makeIfNecessary:NO];
if (fv != nil) {
[fv mouseDown:theEvent];
}
return;
}
}
}
[super mouseDown:theEvent];
}
Now it works exactly like I wanted.

How to achieve this animation with Spritekit?

Question:
How to achieve this animation with Spritekit?
What I've done:
Problem:
1) I can draw all four petals,but once I lift my finger to draw the circle, it will still create a line from the previous point where I lift my finger to the new touches begin point. refer to gif below:
2) How to remove the solid orange line from the view incrementally (mine is too abrupt)?
3) Need to tune the .sks file properties.
4) https://stackoverflow.com/questions/29792443/set-the-initial-state-of-skemitternode
This is my code:
#import "GameScene.h"
#interface GameScene()
#property (nonatomic) SKEmitterNode* fireEmmitter;
#property (nonatomic) SKEmitterNode* fireEmmitter2;
#end
#implementation GameScene
NSMutableArray *_wayPoints;
NSTimer* myTimer;
-(void)didMoveToView:(SKView *)view {
_wayPoints = [NSMutableArray array];
//Setup a background
self.backgroundColor = [UIColor blackColor];
//setup a fire emitter
NSString *fireEmmitterPath = [[NSBundle mainBundle] pathForResource:#"magic" ofType:#"sks"];
_fireEmmitter = [NSKeyedUnarchiver unarchiveObjectWithFile:fireEmmitterPath];
_fireEmmitter.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2 - 200);
_fireEmmitter.name = #"fireEmmitter";
_fireEmmitter.zPosition = 1;
_fireEmmitter.targetNode = self;
_fireEmmitter.particleBirthRate = 0;
[self addChild: _fireEmmitter];
//setup another fire emitter
NSString *fireEmmitterPath2 = [[NSBundle mainBundle] pathForResource:#"fireflies" ofType:#"sks"];
_fireEmmitter2 = [NSKeyedUnarchiver unarchiveObjectWithFile:fireEmmitterPath2];
_fireEmmitter2.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2);
_fireEmmitter2.name = #"fireEmmitter";
_fireEmmitter2.zPosition = 1;
_fireEmmitter2.targetNode = self;
_fireEmmitter2.particleBirthRate = 0;
[self addChild: _fireEmmitter2];
//Setup a LightNode
SKLightNode* light = [[SKLightNode alloc] init];
light.categoryBitMask = 1;
light.falloff = 1;
light.ambientColor = [UIColor whiteColor];
light.lightColor = [[UIColor alloc] initWithRed:1.0 green:1.0 blue:0.0 alpha:0.5];
light.shadowColor = [[UIColor alloc] initWithRed:0.0 green:0.0 blue:0.0 alpha:0.3];
[_fireEmmitter addChild:light];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
CGMutablePathRef ref = CGPathCreateMutable();
CGPoint p = touchPoint;
p = [self.scene convertPointToView:p];
CGPathMoveToPoint(ref, NULL, p.x, p.y);
_fireEmmitter.position = CGPointMake(touchPoint.x, touchPoint.y);
_fireEmmitter.particleBirthRate = 2000;
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
//On Dragging make the emitter with the attached light follow the position
for (UITouch *touch in touches) {
[self addPointToMove:touchPoint];
CGPoint location = [touch locationInNode:self];
[self childNodeWithName:#"fireEmmitter"].position = CGPointMake(location.x, location.y);
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
_fireEmmitter.particleBirthRate = 0;
[self performSelector:#selector(userHasCompletedTheDrawing) withObject:nil afterDelay:3];
}
- (void)userHasCompletedTheDrawing{
CGMutablePathRef path = CGPathCreateMutable();
if (_wayPoints && _wayPoints.count > 0) {
CGPoint p = [(NSValue *)[_wayPoints objectAtIndex:0] CGPointValue];
//p = [self.scene convertPointToView:p];
CGPathMoveToPoint(path, nil, p.x, p.y);
_fireEmmitter2.position = CGPointMake(p.x,p.y);
_fireEmmitter2.particleBirthRate = 1000;
for (int i = 0; i < _wayPoints.count; ++i) {
p = [(NSValue *)[_wayPoints objectAtIndex:i] CGPointValue];
CGPathAddLineToPoint(path, nil, p.x, p.y);
}
SKAction *followTrack = [SKAction followPath:path asOffset:NO orientToPath:YES duration:1];
[_fireEmmitter2 runAction:followTrack completion:^{
_fireEmmitter2.particleBirthRate = 0;
[_fireEmmitter2 runAction:[SKAction waitForDuration:1] completion:^{
//_fireEmmitter2.particleBirthRate = 0;
}];
}];
}
//myTimer = [NSTimer scheduledTimerWithTimeInterval: 0.01 target: self selector: #selector(removePointToMove) userInfo: nil repeats: YES];
[self performSelector:#selector(removeAllPointToMove) withObject:nil afterDelay:1];
}
- (void)addPointToMove:(CGPoint)point {
[_wayPoints addObject:[NSValue valueWithCGPoint:point]];
}
- (void)removeAllPointToMove{
[_wayPoints removeAllObjects];
}
- (void)removePointToMove{
if ([_wayPoints count]>0) {
[_wayPoints removeObjectAtIndex:0];
}
}
- (void)drawLines {
//1
NSMutableArray *temp = [NSMutableArray array];
for(CALayer *layer in self.view.layer.sublayers) {
if([layer.name isEqualToString:#"line"]) {
[temp addObject:layer];
}
}
[temp makeObjectsPerformSelector:#selector(removeFromSuperlayer)];
//3
CAShapeLayer *lineLayer = [CAShapeLayer layer];
lineLayer.name = #"line";
lineLayer.strokeColor = [UIColor orangeColor].CGColor;
lineLayer.fillColor = nil;
lineLayer.lineWidth = 3;
lineLayer.lineJoin = kCALineJoinRound; /* The join style used when stroking the path. Options are `miter', `round'
* and `bevel'. Defaults to `miter'. */
lineLayer.zPosition = -1;
//4
CGPathRef path = [self createPathToMove];
lineLayer.path = path;
CGPathRelease(path);
[self.view.layer addSublayer:lineLayer];
}
- (CGPathRef)createPathToMove {
//1
CGMutablePathRef ref = CGPathCreateMutable();
//2
for(int i = 0; i < [_wayPoints count]; ++i) {
CGPoint p = [_wayPoints[i] CGPointValue];
p = [self.scene convertPointToView:p];
//3
if(i == 0 ) {
CGPathMoveToPoint(ref, NULL, p.x, p.y);
} else {
CGPathAddLineToPoint(ref, NULL, p.x, p.y);
}
}
return ref;
}
-(void)update:(CFTimeInterval)currentTime {
/* Called before each frame is rendered */
[self drawLines];
if ([_wayPoints count]==0) {
[myTimer invalidate];
}
}
#end
This is my .sks files properties:
Concerning your first question, you need to split your CGPathRef into multiple subpaths so that no line gets drawn between the petals and the center. Use the CGPathCloseSubpath function when you are done drawing the petals so that you can call CGPathMoveToPoint and CGPathAddLineToPoint afterwards.

UIPinchGestureRecognizer trouble

Ok, i've read a few posts on this one (ex. UIImageView Gestures (Zoom, Rotate) Question) but I can't seem to fix my problem.
I have the following setup: an SKScene, an SKNode _backgroundLayer and 9 SKSpriteNodes that are tiles that make up the background and are attached to the _backgroundLayer.
Since these 9 tiles make a 3x3 square and they are quite large, I need to be able to zoom in and look at other SKSpriteNodes that will be on top of these 9 background images.
There are two problems:
1) When I pinch to zoom in or zoom out it seems like it is zooming in/out from location (0,0) of the _backgroundLayer and not from the touch location.
2) I have added some bounds so that the user can not scroll out of the 9 background images. In general it works. However, if I zoom in then move towards the top of the 9 background images and then zoom out the bounding conditions go berserk and the user can see the black space outside the background images. I need a way to limit the amount of zooming out that the user can do depending on where he's at.
Any ideas? Thanks!
I include my code below:
#import "LevelSelectScene.h"
#import "TurtleWorldSubScene.h"
#interface LevelSelectScene ()
#property (nonatomic, strong) SKNode *selectedNode;
#end
#implementation LevelSelectScene
{
SKNode *_backgroundLayer;
}
-(id)initWithSize:(CGSize)size {
if (self = [super initWithSize:size]) {
/* Setup your scene here */
_backgroundLayer = [SKNode node];
_backgroundLayer.name = #"backgroundLayer";
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[_backgroundLayer setScale:0.76];
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && IS_WIDESCREEN) {
} else {
[_backgroundLayer setScale:0.36];
}
[self addChild:_backgroundLayer];
SKTexture *backgroundTexture = [SKTexture textureWithImageNamed:#"levelSelect"];
int textureID = 0;
for (int i = 0; i<3; i++) {
for (int j = 0; j<3; j++) {
SKSpriteNode *background = [SKSpriteNode spriteNodeWithTexture:backgroundTexture];
background.anchorPoint = CGPointZero;
background.position = CGPointMake((background.size.width)*i, (background.size.height)*j);
background.zPosition = 0;
background.name = [NSString stringWithFormat:#"background%d", textureID];
textureID++;
[_backgroundLayer addChild:background];
}
}
[TurtleWorldSubScene displayTurtleWorld:self];
}
return self;
}
- (void)didMoveToView:(SKView *)view {
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(handlePanFrom:)];
[[self view] addGestureRecognizer:panGestureRecognizer];
//UITapGestureRecognizer * tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(handleTap:)];
// [self.view addGestureRecognizer:tapRecognizer];
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(handlePinch:)];
[[self view] addGestureRecognizer:pinchGestureRecognizer];
}
- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer {
if (recognizer.state == UIGestureRecognizerStateBegan) {
CGPoint touchLocation = [recognizer locationInView:recognizer.view];
touchLocation = [self convertPointFromView:touchLocation];
SKNode *node = [self nodeAtPoint:touchLocation];
_selectedNode = node;
} else if (recognizer.state == UIGestureRecognizerStateChanged) {
CGPoint translation = [recognizer translationInView:recognizer.view];
translation = CGPointMake(translation.x, -translation.y);
CGPoint initialPosition = CGPointAdd(_backgroundLayer.position, translation);
_backgroundLayer.position = [self boundLayerPos:initialPosition];
[recognizer setTranslation:CGPointZero inView:recognizer.view];
} else if (recognizer.state == UIGestureRecognizerStateEnded) {
float scrollDuration = 0.2;
CGPoint velocity = [recognizer velocityInView:recognizer.view];
CGPoint pos = [_backgroundLayer position];
CGPoint p = CGPointMultiplyScalar(velocity, scrollDuration);
CGPoint newPos = CGPointMake(pos.x + p.x, pos.y - p.y);
newPos = [self boundLayerPos:newPos];
[_backgroundLayer removeAllActions];
SKAction *moveTo = [SKAction moveTo:newPos duration:scrollDuration];
[moveTo setTimingMode:SKActionTimingEaseOut];
[_backgroundLayer runAction:moveTo];
}
}
- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer
{
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
if(_backgroundLayer.xScale*recognizer.scale < 0.76) {
//SKSpriteNode *backgroundTile = (SKSpriteNode *)[_backgroundLayer childNodeWithName:#"background0"];
[_backgroundLayer setScale:0.76];
} else if(_backgroundLayer.xScale*recognizer.scale > 2) {
[_backgroundLayer setScale:2.0];
} else {
[_backgroundLayer runAction:[SKAction scaleBy:recognizer.scale duration:0]];
}
} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone && IS_WIDESCREEN) {
} else {
if(_backgroundLayer.xScale*recognizer.scale < 0.36) {
[_backgroundLayer setScale:0.36];
} else if(_backgroundLayer.xScale*recognizer.scale > 2) {
[_backgroundLayer setScale:2.0];
} else {
[_backgroundLayer runAction:[SKAction scaleBy:recognizer.scale duration:0]];
}
}
recognizer.scale = 1;
}
- (CGPoint)boundLayerPos:(CGPoint)newPos {
SKSpriteNode *backgroundTile = (SKSpriteNode *)[_backgroundLayer childNodeWithName:#"background0"];
CGPoint retval = newPos;
retval.x = MIN(retval.x, 0);
retval.x = MAX(retval.x, -(backgroundTile.size.width*_backgroundLayer.xScale*3)+self.size.width);
retval.y = MIN(retval.y, 0);
retval.y = MAX(retval.y, -(backgroundTile.size.height*_backgroundLayer.xScale*3)+self.size.height);
return retval;
}

Retrigger CABasicAnimation with NSThread in iOS

I am hacking this Core Animation example:
https://github.com/joericioppo/Shape_05
I want to retrigger the animation in response to an NSThread. The NSLogs show up as expected, but the animation itself does not trigger until all sleeps have completed, even though its method has verifiably been called. How can I retrigger this animation every second?
By the way - this is just an example patch I am working on in order to understand the concept. I know that animations can be set to repeat, but this isn't what I want to do, for various reasons. Here's the code, any help would be most welcome, thanks.
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface Shape_05ViewController : UIViewController {
CALayer *rootLayer;
CAShapeLayer *shapeLayer;
CGMutablePathRef pentagonPath;
CGMutablePathRef starPath;
int animationCount;
CABasicAnimation *animation;
}
-(void)startAnimation;
-(void) viewDidLoad;
-(void) startSequence;
-(void) enactSequence;
#end
#import "Shape_05ViewController.h"
#implementation Shape_05ViewController
- (void)loadView
{
UIView *appView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
appView.backgroundColor = [UIColor blackColor];
self.view = appView;
[appView release];
rootLayer = [CALayer layer];
rootLayer.frame = self.view.bounds;
[self.view.layer addSublayer:rootLayer];
//Pentagon Path
pentagonPath = CGPathCreateMutable();
CGPoint center = self.view.center;
CGPathMoveToPoint(pentagonPath, nil, center.x, center.y - 75.0);
for(int i = 1; i < 5; ++i) {
CGFloat x = - 75.0 * sinf(i * 2.0 * M_PI / 5.0);
CGFloat y = - 75.0 * cosf(i * 2.0 * M_PI / 5.0);
CGPathAddLineToPoint(pentagonPath, nil,center.x + x, center.y + y);
}
CGPathCloseSubpath(pentagonPath); //This seems to be fixed in 4.0
//Star Path
starPath = CGPathCreateMutable();
center = self.view.center;
CGPathMoveToPoint(starPath, NULL, center.x, center.y + 75.0);
for(int i = 1; i < 5; ++i) {
CGFloat x = 75.0 * sinf(i * 4.0 * M_PI / 5.0);
CGFloat y = 75.0 * cosf(i * 4.0 * M_PI / 5.0);
CGPathAddLineToPoint(starPath, NULL, center.x + x, center.y + y);
};
CGPathCloseSubpath(starPath);
//Create Shape
shapeLayer = [CAShapeLayer layer];
shapeLayer.path = pentagonPath;
UIColor *fillColor = [UIColor colorWithWhite:0.9 alpha:1.0];
shapeLayer.fillColor = fillColor.CGColor;
shapeLayer.fillRule = kCAFillRuleNonZero;
[rootLayer addSublayer:shapeLayer];
}
-(void) viewDidLoad {
NSLog(#"viewDidLoad");
animationCount = 0;
[NSThread detachNewThreadSelector:#selector(startSequence) toTarget:self withObject:nil];
}
-(void) startSequence {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self enactSequence];
//[NSThread sleepForTimeInterval:100];
[pool release];
}
-(void) enactSequence {
NSLog(#"enactSequence");
for(int i = 0; i < 4; i++) {
[NSThread sleepForTimeInterval:1];
[self performSelector:#selector(startAnimation) withObject:nil];
[rootLayer setNeedsDisplay];
NSLog(#"%i", i);
};
}
-(void)startAnimation
{
NSLog(#"startAnimation");
animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.duration = 0.25;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.repeatCount = 0;
animation.autoreverses = NO;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = YES;
if( (animationCount % 2) == 0) {
animation.fromValue = (id)pentagonPath;
animation.toValue = (id)starPath;
} else {
animation.fromValue = (id)starPath;
animation.toValue = (id)pentagonPath;
};
[shapeLayer addAnimation:animation forKey:#"animatePath"];
animationCount++;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
CGPathRelease(starPath);
CGPathRelease(pentagonPath);
[super dealloc];
}
#end
OK after another Google trawl:
http://forums.macrumors.com/showthread.php?t=749518&highlight=cabasicanimation
I found out about this thing called NSTimer! Another search of this site revealed some good info:
How do I use NSTimer?
And about running NSTimer in its own thread:
Keep an NSThread containing an NSTimer around indefinitely? (iPhone)
So now I can offer this updated code example, which I hope may be useful to someone one day. By the way, I didn't try it yet, but apparently the following can be used to stop the timer:
[myTimer invalidate];
myTimer = nil;
Thanks to all here at this site, not only the most beautifully designed corner of the web but also a total lifesaver!
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#interface Shape_05ViewController : UIViewController {
CALayer *rootLayer;
CAShapeLayer *shapeLayer;
CGMutablePathRef pentagonPath;
CGMutablePathRef starPath;
int animationCount;
CABasicAnimation *animation;
NSTimer *repeatingTimer;
}
#property (assign, readwrite) NSTimer *repeatingTimer;
-(void) startAnimation: (NSTimer*)theTimer;
-(void) viewDidLoad;
-(void) startSequence;
#end
#import "Shape_05ViewController.h"
#implementation Shape_05ViewController
#synthesize repeatingTimer;
- (void)loadView
{
UIView *appView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
appView.backgroundColor = [UIColor blackColor];
self.view = appView;
[appView release];
rootLayer = [CALayer layer];
rootLayer.frame = self.view.bounds;
[self.view.layer addSublayer:rootLayer];
//Pentagon Path
pentagonPath = CGPathCreateMutable();
CGPoint center = self.view.center;
CGPathMoveToPoint(pentagonPath, nil, center.x, center.y - 75.0);
for(int i = 1; i < 5; ++i) {
CGFloat x = - 75.0 * sinf(i * 2.0 * M_PI / 5.0);
CGFloat y = - 75.0 * cosf(i * 2.0 * M_PI / 5.0);
CGPathAddLineToPoint(pentagonPath, nil,center.x + x, center.y + y);
}
CGPathCloseSubpath(pentagonPath); //This seems to be fixed in 4.0
//Star Path
starPath = CGPathCreateMutable();
center = self.view.center;
CGPathMoveToPoint(starPath, NULL, center.x, center.y + 75.0);
for(int i = 1; i < 5; ++i) {
CGFloat x = 75.0 * sinf(i * 4.0 * M_PI / 5.0);
CGFloat y = 75.0 * cosf(i * 4.0 * M_PI / 5.0);
CGPathAddLineToPoint(starPath, NULL, center.x + x, center.y + y);
};
CGPathCloseSubpath(starPath);
//Create Shape
shapeLayer = [CAShapeLayer layer];
shapeLayer.path = pentagonPath;
UIColor *fillColor = [UIColor colorWithWhite:0.9 alpha:1.0];
shapeLayer.fillColor = fillColor.CGColor;
shapeLayer.fillRule = kCAFillRuleNonZero;
[rootLayer addSublayer:shapeLayer];
}
-(void) viewDidLoad {
NSLog(#"viewDidLoad");
animationCount = 0;
[NSThread detachNewThreadSelector:#selector(startSequence) toTarget:self withObject:nil];
}
-(void) startSequence {
NSLog(#"startSequence");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:#selector(startAnimation:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] run];
self.repeatingTimer = timer;
[pool release];
}
-(void)startAnimation: (NSTimer*)theTimer {
NSLog(#"startAnimation");
animation = [CABasicAnimation animationWithKeyPath:#"path"];
animation.duration = 0.25;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
animation.repeatCount = 0;
animation.autoreverses = NO;
animation.fillMode = kCAFillModeForwards;
animation.removedOnCompletion = NO;
if( (animationCount % 2) == 0) {
animation.fromValue = (id)pentagonPath;
animation.toValue = (id)starPath;
} else {
animation.fromValue = (id)starPath;
animation.toValue = (id)pentagonPath;
};
[shapeLayer addAnimation:animation forKey:#"animatePath"];
animationCount++;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)dealloc
{
CGPathRelease(starPath);
CGPathRelease(pentagonPath);
[super dealloc];
}
#end