Issue with Drawing on UIImage - ios

I am using the following code to Draw over an image. All the touch delegates are working, but the drawing is not rendered over the UIImage. Here is the code. I am not able to identify the issue. Thanks in advance.
- (id)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
[self setupVariables];
}
return self;
}
- (void)drawPic:(UIImage *)thisPic {
myPic = thisPic;
[myPic retain];
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect {
float newHeight;
float newWidth;
float xPos;
float yPos;
float ratio;
if (myPic != NULL) {
ratio = myPic.size.height/460;
if (myPic.size.width/320 > ratio) {
ratio = myPic.size.width/320;
}
newHeight = myPic.size.height/ratio;
newWidth = myPic.size.width/ratio;
xPos = (320 - newWidth) / 2;
yPos = (460 - newHeight) / 2;
[myPic drawInRect:CGRectMake(xPos, yPos, newWidth, newHeight)];
}
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [[event allTouches] allObjects];
if ([allTouches count] > 1) {
return;
}
else {
[self drawPoint:[allTouches objectAtIndex:0]];
}
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [[event allTouches] allObjects];
if ([allTouches count] > 1) {
return;
}
else {
[self drawPoint:[allTouches objectAtIndex:0]];
self.previousPoint = nil;
self.point = nil;
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [[event allTouches] allObjects];
if ([allTouches count] > 1) {
return;
}
else {
[self drawPoint:[allTouches objectAtIndex:0]];
self.previousPoint = nil;
self.point = nil;
}
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSArray *allTouches = [[event allTouches] allObjects];
if ([allTouches count] > 1) {
return;
}
else {
[self drawPoint:[allTouches objectAtIndex:0]];
}
}
- (void)dealloc {
CGContextRelease(offScreenBuffer);
[point release];
[previousPoint release];
[super dealloc];
}
- (void)setupVariables {
self.point = nil;
self.previousPoint = nil;
offScreenBuffer = [self setupBuffer];
}
- (CGContextRef)setupBuffer {
CGSize size = self.bounds.size;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL,size.width,size.height,8,size.width*4, colorSpace,kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
CGContextTranslateCTM(context, 0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
return context;
}
- (void)drawToBuffer {
// Red Gr Blu Alpha
CGFloat color[4] = {0.0, 1.0, 0.0, 1.0};
if (self.previousPoint != nil) {
CGContextSetRGBStrokeColor(offScreenBuffer, color[0], color[1], color[2], color[3]);
CGContextBeginPath(offScreenBuffer);
CGContextSetLineWidth(offScreenBuffer, 10.0);
CGContextSetLineCap(offScreenBuffer, kCGLineCapRound);
CGContextMoveToPoint(offScreenBuffer, previousPoint.location.x, previousPoint.location.y);
CGContextAddLineToPoint(offScreenBuffer, point.location.x, point.location.y);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeColor);
CGContextDrawPath(offScreenBuffer, kCGPathStroke);
}
}
- (void)drawPoint:(UITouch *)touch {
PointLocation *currentLoc = [[PointLocation alloc] init];
currentLoc.location = [touch locationInView:self];
self.previousPoint = self.point;
self.point = currentLoc;
[self drawToBuffer];
[self setNeedsDisplay];
[currentLoc release];
}

It's very simple. You need to do all your drawing in drawRect: and you're only drawing the image in drawRect:, so that's why you only see the image.

-(void)drawPic:(UIImage *)thisPic {
//code for UIViewContentModeScaleAspectFit if needed
self.backgroundColor = [UIColor colorWithPatternImage:thisPic];
[self setNeedsDisplay];
}
Do Not use this in drawRect Method:
[myPic drawInRect:CGRectMake(xPos, yPos, newWidth, newHeight)];
Edit
- (void)drawRect:(CGRect)rect {
if (!myDrawing) {
// CGFloat scale = 0.5;
// CATransform3D transform = CATransform3DMakeScale(scale, scale, scale);
// [self layer].transform = transform;
myDrawing = [[NSMutableArray alloc] initWithCapacity:0];
self.lineOnOffArray = [[NSMutableArray alloc] initWithCapacity:0];
//arrPenThickness = [[NSMutableArray alloc] initWithCapacity:0];
}
CGContextRef ctx = UIGraphicsGetCurrentContext();
if ([myDrawing count] > 0) {
for (int i = 0 ; i < [myDrawing count] ; i++) {
NSArray *thisArray = [myDrawing objectAtIndex:i];
NSString *onOffFlag = [self.lineOnOffArray objectAtIndex:i];
if (([thisArray count] > 2) && (onOffFlag == #"1")){
float penT = [[arrPenThickness objectAtIndex:i] floatValue];
NSString* penC = [arrPenColors objectAtIndex:i];
NSArray *arr = [penC componentsSeparatedByString:#","];
float r = [[arr objectAtIndex:0]floatValue];
float g = [[arr objectAtIndex:1]floatValue];
float b = [[arr objectAtIndex:2]floatValue];
float a = [[arr objectAtIndex:3]floatValue];
CGContextSetRGBStrokeColor(ctx,
r/255.0,
g/255.0,
b/255.0,
a);
CGContextSetLineCap(ctx, kCGLineCapRound);
CGContextSetLineWidth(ctx, penT);
float thisX = [[thisArray objectAtIndex:0] floatValue];
float thisY = [[thisArray objectAtIndex:1] floatValue];
CGContextBeginPath(ctx);
for (int j = 2; j < [thisArray count] ; j+=2) {
CGContextMoveToPoint(ctx, thisX, thisY);
thisX = [[thisArray objectAtIndex:j] floatValue];
thisY = [[thisArray objectAtIndex:j+1] floatValue];
CGContextAddLineToPoint(ctx, thisX,thisY);
}
CGContextStrokePath(ctx);
}
}
}
}

Related

Crash EXC_BAD_ACCESS on touch method

I am currently working on a game which, seems to crash when accessing a certain part of the code which involves touching an item.
Here is the part of the code that crashes;
drawOn = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, currentDrawingImage.size.width/2, currentDrawingImage.size.height/2)];
The full method is here;
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
BOOL foundExtra = NO;
UITouch *touch = [[event allTouches] anyObject];
for(int i = 0; i < [extrasArray count]; i++)
{
if([[[extrasArray objectAtIndex:i] objectForKey:#"tag"] intValue] == [touch view].tag)
{
touchedExtra = YES;
lastTouchedExtra = (int)[touch view].tag;
foundExtra = YES;
}
}
if(foundExtra == NO)
{
if(movingStopped == NO)
{
drawOn = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, currentDrawingImage.size.width/2, currentDrawingImage.size.height/2)];
drawOn.image = currentDrawingImage;
drawOn.tag = lastTag + 1;
lastTag++;
CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
drawOn.center = CGPointMake(touchPoint.x, touchPoint.y);
[bigView addSubview:drawOn];
lastTouchedPoint = touchPoint;
}
}
}
- (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
if(touchedExtra == YES)
{
CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
UITouch *touch = [touches anyObject];
int indexIngr = 0;
for(int i = 0; i < [extrasArray count]; i++)
{
if([[[extrasArray objectAtIndex:i] objectForKey:#"tag"] intValue] == [touch view].tag)
{
indexIngr = i;
[touch view].center = touchPoint;
}
}
NSMutableDictionary *md = [[NSMutableDictionary alloc] init];
[md setObject:[[extrasArray objectAtIndex:indexIngr] objectForKey:#"pic"] forKey:#"pic"];
[md setObject:NSStringFromCGRect([touch view].frame) forKey:#"frame"];
[md setObject:[NSString stringWithFormat:#"%d", (int)[touch view].tag] forKey:#"tag"];
[extrasArray replaceObjectAtIndex:indexIngr withObject:md];
// if([touch view].tag > 0)
// {
// [touch view].center = touchPoint;
//
// int tagLabel = [touch view].tag;
// NSMutableDictionary *md = [[NSMutableDictionary alloc] init];
// [md setObject:[[ingredients objectAtIndex:tagLabel - 1] objectForKey:#"pic"] forKey:#"pic"];
// [md setObject:NSStringFromCGRect([touch view].frame) forKey:#"frame"];
//
// [ingredients replaceObjectAtIndex:tagLabel - 1 withObject:md];
// }
}
else if(lastDecoration == 1)//draw on apple
{
if(movingStopped == NO)
{
CGPoint touchPoint = [[touches anyObject] locationInView:self.view];
if([self isFarEnoughFrom:touchPoint])
{
drawOn = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, currentDrawingImage.size.width/2, currentDrawingImage.size.height/2)];
drawOn.image = currentDrawingImage;
drawOn.tag = lastTag;
drawOn.center = CGPointMake(touchPoint.x, touchPoint.y);
[bigView addSubview:drawOn];
//[self.view insertSubview:drawOn belowSubview:backButton];
lastTouchedPoint = touchPoint;
}
}
}
}
- (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event
{
touchedExtra = NO;
//movingStopped = YES;
lastTouchedExtra = -1;
}
The drawOnChosen method is used also;
- (void)drawOnChosen:(UIButton*)sender
{
[(AppDelegate*)[[UIApplication sharedApplication] delegate] playSoundEffect:1];
currentDrawingImage = [UIImage imageNamed:[NSString stringWithFormat:#"drawon%d.png", (int)sender.tag]];
movingStopped = NO;
lastDecoration = 1;
[UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^
{
decorationsView.frame = CGRectMake(0, -[[UIScreen mainScreen] bounds].size.height, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height);
} completion:^(BOOL finished)
{
[decorationsView removeFromSuperview];
}];
}

Objective-C OpenGL how to rotate, scale

I have the following source code where i can draw some objects to the screen but i want to rotate and scale the drawed object and nothing happens when i am touching the screen. (In the log i can see if i am doing a pan gesture or a pinch gesture so the detection is ok)
What am i doing wrong?
UPDATE
Now it moves (instead of rotation) maybe i rotate it not around the center of the pointcloud. I tried to move it to center but now nothing is on the screen. Here is the updated Code:
#import <QuartzCore/QuartzCore.h>
#import <OpenGLES/EAGLDrawable.h>
#import "EAGLView.h"
#import "VertexPoint.h"
#import "CamOnMap-Swift.h"
#import <Math.h>
#define USE_DEPTH_BUFFER 1
#define DEGREES_TO_RADIANS(__ANGLE) ((__ANGLE) / 180.0 * M_PI)
// A class extension to declare private methods
#interface EAGLView ()
#property (nonatomic, retain) EAGLContext *context;
//#property (nonatomic, assign) NSTimer *animationTimer;
- (BOOL) createFramebuffer;
- (void) destroyFramebuffer;
#end
#implementation EAGLView
#synthesize context;
//#synthesize animationTimer;
//#synthesize animationInterval;
// You must implement this method
+ (Class)layerClass {
return [CAEAGLLayer class];
}
-(id)initWithCoder:(NSCoder *)aDecoder{
NSLog(#"Ide eljutottam ez az initWithCoder");
TOUCH_ROT_FACTOR = (180.0 / 320.0);
if ((self = [super initWithCoder:aDecoder])) {
// Get the layer
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
eaglLayer.opaque = YES;
eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:NO], kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8, kEAGLDrawablePropertyColorFormat, nil];
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
if (!context || ![EAGLContext setCurrentContext:context]) {
//[self release];
return nil;
}
// animationInterval = 1.0 / 60.0;
[self setupView];
}
return self;
}
- (void)setupView {
const GLfloat zNear = 0.1, zFar = 1000.0, fieldOfView = 60.0;
GLfloat size;
glEnable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
size = zNear * tanf(DEGREES_TO_RADIANS(fieldOfView) / 2.0);
//Grab the size of the screen
CGRect rect = self.frame;
glFrustumf(-size, size,
-size / (rect.size.width / rect.size.height),
size / (rect.size.width / rect.size.height),
zNear, zFar);
glViewport(0, 0, rect.size.width, rect.size.height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//Initialize touchLocation to 0, 0
// touchLocation = CGPointMake(rect.size.width/2, rect.size.height/2);
// touchLocation = CGPointMake(0, 0);
// GLfloat x = (touchLocation.x);
// GLfloat y = (touchLocation.y);
//translate the triangle
// glTranslatef(x, y, -10.0);
multitouch_distance_start = 0;
viewDistance = -100;
[self setupGestures];
[self getPly];
}
- (void)setupGestures{
[self setUserInteractionEnabled:true];
[self setMultipleTouchEnabled:true];
pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:#selector(pinchHandler:)];
panGesture =[[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(panHandler:)];
[self addGestureRecognizer:pinchGesture];
[self addGestureRecognizer:panGesture];
};
-(VertexPoint*)center:(NSMutableArray *)vertices2{
float sum_x =0.0f;
float sum_y =0.0f;
float sum_z =0.0f;
for (int i=0; i<vertices2.count; i++) {
VertexPoint *point =vertices2[i];
sum_x +=point.x;
sum_y +=point.y;
sum_z +=point.z;
}
center_ = [[VertexPoint alloc] init];
GLfloat point[] = {(sum_x / vertices2.count),(sum_y / vertices2.count), (sum_z / vertices2.count)};
[center_ setPosition:point];
return center_;
}
-(float)multiTouchDistance:(UIPinchGestureRecognizer *) recognizer{
float x1 = [recognizer locationOfTouch:0 inView:self].x;
float y1 = [recognizer locationOfTouch:0 inView:self].y;
float x2 = [recognizer locationOfTouch:1 inView:self].x;
float y2 = [recognizer locationOfTouch:1 inView:self].y;
float dx = x2 - x1;
float dy = y2 - y1;
return sqrt(dx*dx + dy*dy);
}
- (void)pinchHandler:(UIPinchGestureRecognizer *)recognizer {
glPopMatrix();
float d = [self multiTouchDistance:recognizer];
NSLog(#"d: %f",d);
if(d > 0.0f)multitouch_distance_start = d;
viewDistance *= multitouch_distance_start / d;
multitouch_distance_start = d;
//glScalef(recognizer.scale, recognizer.scale, recognizer.scale);
//recognizer.scale = 1;
NSLog(#"viewDistance: %f",viewDistance);
glPushMatrix();
[self render];
}
- (void)panHandler:(UIPanGestureRecognizer *)recognizer {
if(recognizer.state == UIGestureRecognizerStateBegan){
CGPoint translation = [recognizer translationInView:self];
xPrev = translation.x;
yPrev = translation.y;
}
if(recognizer.state == UIGestureRecognizerStateChanged){
glPopMatrix();
CGPoint translation = [recognizer translationInView:self];
GLfloat dx = translation.x - xPrev;
GLfloat dy = translation.y - yPrev;
xAngle += ((dx) * (TOUCH_ROT_FACTOR));
yAngle += ((dy) * (TOUCH_ROT_FACTOR));
// glRotatef(xAngle,1,0,0);
// glRotatef(yAngle,0,1,0);
xPrev = translation.x;
yPrev = translation.y;
glPushMatrix();
NSLog(#"pan");
[self render];
}
};
-(void)completionHandler:(NSString *) data{
// NSLog(#"%#",data);
NSArray *dataArray = [data componentsSeparatedByString:#"\n"];
vertices = [[NSMutableArray alloc] init];
for(NSInteger i = 14; i < dataArray.count; i++ ){
NSArray *row = [dataArray[i] componentsSeparatedByString:#" "];
if(![dataArray[i] isEqual: #""]){
VertexPoint *point = [[VertexPoint alloc] init];
GLfloat a[] = { [[row objectAtIndex:0] floatValue], [[row objectAtIndex:1] floatValue], [[row objectAtIndex:2] floatValue]};
[point setPosition:a];
GLfloat b[] = { [[row objectAtIndex:6] floatValue],[[row objectAtIndex:7] floatValue], [[row objectAtIndex:8] floatValue], [[row objectAtIndex:9] floatValue]};
[point setColor:b];
[vertices addObject:point];
}
}
long vcount = [vertices count] * 3; // * 2 for the two coordinates of a loc object
glVertices = (GLfloat *)malloc(vcount * sizeof(GLfloat));
int currIndex = 0;
for (VertexPoint *loc in vertices) {
glVertices[currIndex++] = (loc.x);
glVertices[currIndex++] =(loc.y);
glVertices[currIndex++] =(loc.z);
}
long ccount = [vertices count] * 4;
glColors = (GLfloat *)malloc(ccount * sizeof(GLfloat));
int currColorIndex = 0;
for(VertexPoint *color in vertices){
glColors[currColorIndex++] = (color.r);
glColors[currColorIndex++] = (color.g);
glColors[currColorIndex++] = (color.b);
glColors[currColorIndex++] = (color.a);
}
center_ = [self center: vertices];
glTranslatef(0, 0, -100);
// glTranslatef(-1 * center_.x, -1 * center_.y, -1 * center_.z);
NSLog(#"x: %f, y: %f, z:%f",-1 * center_.x,-1 * center_.y,-1 * center_.z);
[self drawView];
};
-(void)getPly{
GlobalDataFunctions *globalDataFunctions = [[GlobalDataFunctions alloc] init];
NSString *ply = [globalDataFunctions selectedPly];
NSLog(#"%#",ply);
RestClient *restClient = [[RestClient alloc] init];
NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:#"username"];
NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:#"password"];
[restClient getPly: username password:password ply:ply myComletionHandler: ^(NSString *data){
[self completionHandler:data];
}];
};
- (void)drawView {
NSLog(#"drawView");
//setting up the draw content
[EAGLContext setCurrentContext:context];
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
//Draw stuff
//reset matrix to identity
glLoadIdentity();
//rough approximation of screen to current 3D space
GLfloat x = (touchLocation.x - 160.0) / 38.0;
GLfloat y = (240.0 - touchLocation.y) / 38.0;
//translate the triangle
glTranslatef(x, y, -1.0);
[self render];
}
-(void)render{
NSLog(#"render");
center_ = [self center: vertices];
// glTranslatef(-1 * center_.x, -1 * center_.y, -1 * center_.z);
//clear the back color back to our original color and depth buffer
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//rough approximation of screen to current 3D space
//set the format and location for verticies
glVertexPointer(3, GL_FLOAT, 0, glVertices);
//set the opengl state
glEnableClientState(GL_VERTEX_ARRAY);
//set the format and location for colors
glColorPointer(4, GL_FLOAT, 0, glColors);
//set the opengl state
glEnableClientState(GL_COLOR_ARRAY);
glPointSize(3);
//draw the triangles
// glTranslatef(0,0,viewDistance);
// glTranslatef(-1 * center_.x, -1 * center_.y, -1 * center_.z);
glDrawArrays(GL_POINTS, 0, vertices.count);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
//show the render buffer
[context presentRenderbuffer:GL_RENDERBUFFER_OES];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
touchLocation = [touch locationInView:self];
NSLog(#"touch");
[self drawView];
}
- (void)layoutSubviews {
[EAGLContext setCurrentContext:context];
[self destroyFramebuffer];
[self createFramebuffer];
[self drawView];
}
- (BOOL)createFramebuffer {
glGenFramebuffersOES(1, &viewFramebuffer);
glGenRenderbuffersOES(1, &viewRenderbuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
if (USE_DEPTH_BUFFER) {
glGenRenderbuffersOES(1, &depthRenderbuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, backingWidth, backingHeight);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
}
if(glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
NSLog(#"failed to make complete framebuffer object %x", glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES));
return NO;
}
return YES;
}
- (void)destroyFramebuffer {
glDeleteFramebuffersOES(1, &viewFramebuffer);
viewFramebuffer = 0;
glDeleteRenderbuffersOES(1, &viewRenderbuffer);
viewRenderbuffer = 0;
if(depthRenderbuffer) {
glDeleteRenderbuffersOES(1, &depthRenderbuffer);
depthRenderbuffer = 0;
}
}
And here can you find a sample input data: http://pastebin.com/rcrfZdyt

iOS CALayer convertPoint:fromLayer: message sent to deallocated instance

I have a class with a square made of bezierPaths, you can change the size of the square by pressing near a side and drag it.
Right now i can drag and release one time, the next time i get the following error:
2015-01-20 14:20:36.356 BezierPaths[196:3437] *** -[CALayer convertPoint:fromLayer:]: message sent to deallocated instance 0x1742251c0
Why doesnt it work the 2nd time?
This is the class:
#implementation EditBezierView
{
UIBezierPath *path;
UIImage *incrementalImage;
CGPoint pts[9];
NSMutableArray *pathPoints;
NSMutableArray *controlPoints;
BOOL pressedPoint;
int index;
float xStart;
float yStart;
int closestIndex;
CGPoint closestComparePoint;
bool moveControl;
int counter;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super initWithCoder:aDecoder])
{
[self setMultipleTouchEnabled:NO];
[self setBackgroundColor:[UIColor clearColor]];
path = [UIBezierPath bezierPath];
[path setLineWidth:1.0];
pathPoints = [NSMutableArray array];
controlPoints = [NSMutableArray array];
}
return self;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setMultipleTouchEnabled:NO];
path = [UIBezierPath bezierPath];
[path setLineWidth:2.0];
counter = 0;
}
return self;
}
- (void)initValues
{
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(47.0, 130.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(14.0, 230.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(26.0, 150.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(22.0, 320.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(9.0, 270.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(90.0, 420.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(24.0, 380.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(230.0, 420.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(170.0, 460.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(300.0, 320.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(280.0, 390)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(307.0, 220.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(315.0, 260.0)]];
[pathPoints addObject:[NSValue valueWithCGPoint:CGPointMake(270.0, 130.0)]];
[controlPoints addObject:[NSValue valueWithCGPoint:CGPointMake(300.0, 160.0)]];
[self drawPaths];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
[[UIColor blueColor] setStroke];
[path stroke];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
counter++;
NSLog(#"%d", counter);
[self.layer.sublayers makeObjectsPerformSelector:#selector(removeFromSuperlayer)];
UITouch *currentTouch = [touches anyObject];
CGPoint startPt = [currentTouch locationInView:self];
if(moveControl)
{
float xOs = [(NSValue*)[controlPoints objectAtIndex:closestIndex] CGPointValue].x;
float yOs = [(NSValue*)[controlPoints objectAtIndex:closestIndex] CGPointValue].y;
[controlPoints replaceObjectAtIndex:closestIndex withObject:[NSValue valueWithCGPoint:CGPointMake(xOs - (xStart-startPt.x), yOs - (yStart - startPt.y))]];
}
else
{
float xOs = [(NSValue*)[pathPoints objectAtIndex:closestIndex] CGPointValue].x;
float yOs = [(NSValue*)[pathPoints objectAtIndex:closestIndex] CGPointValue].y;
[pathPoints replaceObjectAtIndex:closestIndex withObject:[NSValue valueWithCGPoint:CGPointMake(xOs - (xStart-startPt.x), yOs - (yStart - startPt.y))]];
}
[self drawPaths];
xStart = startPt.x;
yStart = startPt.y;
}
- (void)drawPaths
{
path = [UIBezierPath bezierPath];
for(int i = 1; i < [pathPoints count]; i++)
{
//Draw path
[path moveToPoint:((NSValue*)[pathPoints objectAtIndex:i-1]).CGPointValue];
[path addQuadCurveToPoint:((NSValue*)[pathPoints objectAtIndex:i]).CGPointValue controlPoint:((NSValue*)[controlPoints objectAtIndex:i-1]).CGPointValue];
//Draw points
if(i == 1)
{
[self addrectangle:((NSValue*)[pathPoints objectAtIndex:i-1]).CGPointValue];
[self addrectangle:((NSValue*)[pathPoints objectAtIndex:i]).CGPointValue];
[self addQuadrectangle:((NSValue*)[controlPoints objectAtIndex:i-1]).CGPointValue];
}
else
{
[self addrectangle:((NSValue*)[pathPoints objectAtIndex:i]).CGPointValue];
[self addQuadrectangle:((NSValue*)[controlPoints objectAtIndex:i-1]).CGPointValue];
}
}
[self setNeedsDisplay];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *currentTouch = [touches anyObject];
CGPoint startPt = [currentTouch locationInView:self];
closestComparePoint = startPt;
xStart = startPt.x;
yStart = startPt.y;
[self findNearestPoint];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
//[self drawPath];
}
-(void)findNearestPoint
{
int pathClosestIndex = 0;
CGFloat xDist;
CGFloat yDist;
CGFloat Controldistance = 12401240;
CGFloat Pathdistance = 12401240;
for(int i = 0; i < [controlPoints count]; i++)
{
xDist = ABS([(NSValue*)[controlPoints objectAtIndex:i] CGPointValue].x - closestComparePoint.x);
yDist = ABS([(NSValue*)[controlPoints objectAtIndex:i] CGPointValue].y - closestComparePoint.y);
if(sqrt((xDist * xDist) + (yDist * yDist)) < Controldistance)
{
Controldistance = sqrt((xDist * xDist) + (yDist * yDist));
closestIndex = i;
}
}
for(int i = 0; i < [pathPoints count]; i++)
{
xDist = ABS([(NSValue*)[pathPoints objectAtIndex:i] CGPointValue].x - closestComparePoint.x);
yDist = ABS([(NSValue*)[pathPoints objectAtIndex:i] CGPointValue].y - closestComparePoint.y);
if(sqrt((xDist * xDist) + (yDist * yDist)) < Pathdistance)
{
Pathdistance = sqrt((xDist * xDist) + (yDist * yDist));
pathClosestIndex = i;
}
}
if(Pathdistance < Controldistance)
{
moveControl = NO;
closestIndex = pathClosestIndex;
}
else
{
moveControl = YES;
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
[self touchesEnded:touches withEvent:event];
pressedPoint = NO;
}
-(void)removeRectangles{
[self.layer.sublayers makeObjectsPerformSelector:#selector(removeFromSuperlayer)];
}
-(void)addrectangle:(CGPoint) center{
int offset = 8;
UIBezierPath *path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointMake(center.x - offset, center.y - offset)];
// # Entry Point with 10px white frame
[path2 moveToPoint:CGPointMake(center.x - offset, center.y - offset)];
// # Keeping 10px frame with iPhone's 450 on y-axis
[path2 addLineToPoint:CGPointMake(center.x - offset, center.y + offset)];
// path2 Substracting 10px for frame on x-axis, and moving 450 in y-axis
[path2 addLineToPoint:CGPointMake(center.x + offset, center.y + offset)];
// # Moving up to 1st step 10px line, 310px on the x-axis
[path2 addLineToPoint:CGPointMake(center.x + offset, center.y - offset)];
// # Back to entry point
[path2 addLineToPoint:CGPointMake(center.x - offset, center.y - offset)];
// 4th Create a CAShapeLayer that uses that UIBezierPath:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path2 CGPath];
shapeLayer.strokeColor = [[UIColor blueColor] CGColor];
shapeLayer.lineWidth = 1.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
// 5th add shapeLayer as sublayer inside layer view
[self.layer addSublayer:shapeLayer];
}
-(void)addQuadrectangle:(CGPoint) center{
int offset = 4;
UIBezierPath *path2 = [UIBezierPath bezierPath];
[path2 moveToPoint:CGPointMake(center.x - offset, center.y - offset)];
// # Entry Point with 10px white frame
[path2 moveToPoint:CGPointMake(center.x - offset, center.y - offset)];
// # Keeping 10px frame with iPhone's 450 on y-axis
[path2 addLineToPoint:CGPointMake(center.x - offset, center.y + offset)];
// path2 Substracting 10px for frame on x-axis, and moving 450 in y-axis
[path2 addLineToPoint:CGPointMake(center.x + offset, center.y + offset)];
// # Moving up to 1st step 10px line, 310px on the x-axis
[path2 addLineToPoint:CGPointMake(center.x + offset, center.y - offset)];
// # Back to entry point
[path2 addLineToPoint:CGPointMake(center.x - offset, center.y - offset)];
// 4th Create a CAShapeLayer that uses that UIBezierPath:
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path2 CGPath];
shapeLayer.strokeColor = [[UIColor redColor] CGColor];
shapeLayer.lineWidth = 1.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
// 5th add shapeLayer as sublayer inside layer view
[self.layer addSublayer:shapeLayer];
}
-(int)findOrigoInX
{
int closestToX = [(NSValue *)[pathPoints firstObject] CGPointValue].x;
for(int i = 1; i < [pathPoints count]; i++)
{
if([(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].x < closestToX)
{
closestToX = [(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].x;
}
}
return closestToX;
}
-(int)findOrigoInY
{
int closestToY = [(NSValue *)[pathPoints firstObject] CGPointValue].y;
for(int i = 1; i < [pathPoints count]; i++)
{
if([(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].y > closestToY)
{
closestToY = [(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].y;
}
}
return closestToY;
}
-(NSMutableArray*)generateKoordinateArray
{
NSLog(#"count in pathPoints : %lu", (unsigned long)[pathPoints count]);
NSMutableArray *storeArray = [[NSMutableArray alloc] init];
BezierCsvFormat *storeBezier = [[BezierCsvFormat alloc] init];
NSString *stringValueX;
NSString *stringValueY;
int xOffset = [self findOrigoInX];
NSLog(#"x offset : %d", xOffset);
int yOffset = [self findOrigoInY];
NSLog(#"y offset : %d", yOffset);
for(int i = 1; i < [pathPoints count]; i++)
{
storeBezier = [[BezierCsvFormat alloc] init];
stringValueX = [NSString stringWithFormat:#"%d", (int)[(NSValue *)[pathPoints objectAtIndex:i-1] CGPointValue].x - xOffset];
stringValueY = [NSString stringWithFormat:#"%d", ABS((int)[(NSValue *)[pathPoints objectAtIndex:i-1] CGPointValue].y - yOffset)];
[storeBezier setp0:[NSString stringWithFormat:#"%#,%#",stringValueX, stringValueY]];
stringValueX = [NSString stringWithFormat:#"%d", (int)[(NSValue *)[controlPoints objectAtIndex:i-1] CGPointValue].x - xOffset];
int multiplicator = 1;
if((int)[(NSValue *)[controlPoints objectAtIndex:i-1] CGPointValue].y > yOffset)
{
multiplicator = multiplicator * -1;
}
stringValueY = [NSString stringWithFormat:#"%d", multiplicator * ABS((int)[(NSValue *)[controlPoints objectAtIndex:i-1] CGPointValue].y - yOffset)];
[storeBezier setp1:[NSString stringWithFormat:#"%#,%#",stringValueX, stringValueY]];
stringValueX = [NSString stringWithFormat:#"%d", (int)[(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].x - xOffset];
stringValueY = [NSString stringWithFormat:#"%d", ABS((int)[(NSValue *)[pathPoints objectAtIndex:i] CGPointValue].y - yOffset)];
[storeBezier setp2:[NSString stringWithFormat:#"%#,%#",stringValueX, stringValueY]];
[storeArray addObject:storeBezier];
}
NSLog(#"count in storeArray : %lu", (unsigned long)[storeArray count]);
return storeArray;
}
- (NSMutableArray*)printCoordinateSystem
{
NSMutableArray *tempArray = [self generateKoordinateArray];
return tempArray;
NSLog(#"count in tempArray : %lu", (unsigned long)[tempArray count]);
for(int i = 0; i < [tempArray count]; i++)
{
NSLog(#"p0 : %# p1 : %# p2 : %#", [(BezierCsvFormat*)[tempArray objectAtIndex:i] getp0], [(BezierCsvFormat*)[tempArray objectAtIndex:i] getp1], [(BezierCsvFormat*)[tempArray objectAtIndex:i] getp2]);
}
}
-(void)resetView{
#try {
[path removeAllPoints];
pathPoints = [NSMutableArray array];
[self.subviews makeObjectsPerformSelector:#selector(removeFromSuperview)];
[self.layer.sublayers makeObjectsPerformSelector:#selector(removeFromSuperlayer)];
[self setNeedsDisplay];
}
#catch (NSException *exception) {
[self resetView];
}
#finally {
}
}

IOS - Collision Detection on Sprites using Cocos2d

In this game I have asteroids flying down from to top of screen, and a ship you can move freely, but I have added some collision detection and it does not seem to work in the update method when I call [self scheduleupdate];
// Import the interfaces
#import "HelloWorldLayer.h"
// Needed to obtain the Navigation Controller
#import "AppDelegate.h"
#pragma mark - HelloWorldLayer
// HelloWorldLayer implementation
#implementation HelloWorldLayer
// Helper class method that creates a Scene with the HelloWorldLayer as the only child.
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
-(id) init
{
if( (self=[super init]) ) {
self.isTouchEnabled = YES;
moveLeft = NO;
moveRight = NO;
speed = 3;
fireSpeed = 8;
fireArray = [[NSMutableArray alloc] init];
CGSize winSize = [[CCDirector sharedDirector] winSize];
CCSprite *bg = [[CCSprite alloc] initWithFile:#"space_bg.jpg"];
[bg setPosition:ccp(160, 240)];
CGSize imageSize = bg.contentSize;
bg.scaleX = winSize.width / imageSize.width;
bg.scaleY = winSize.height / imageSize.height;
bg.position = ccp(winSize.width/2, winSize.height/2);
[self addChild:bg];
ship = [[CCSprite alloc] initWithFile:#"ship.png"];
[ship setPosition:ccp(100, 100)];
[self addChild:ship];
[self schedule:#selector(fireLoop:)];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
target:self
selector:#selector(fireCreate)
userInfo:nil
repeats:YES];
asteroidArray = [[NSMutableArray alloc] init];
for(int i = 0; i < 100; ++i) {
CCSprite *asteroid = [[CCSprite alloc] initWithFile:#"asteroid1.png"];
[asteroidArray addObject:asteroid];
}
[self asteroidCreate];
[self scheduleUpdate];
}
return self;
}
CCSpriteBatchNode *spriteSheet;
NSMutableArray *asteroidAnimFrames;
- (float)randomValueBetween:(float)low andValue:(float)high {
return (((float) arc4random() / 0xFFFFFFFFu) * (high - low)) + low;
}
-(void)updtate:(ccTime)dt{
CGPoint shipPosition = [ship position];
for(int i = 0; i < asteroidArray.count; i++){
CCSprite *asteroid = [asteroidArray objectAtIndex:i];
if (CGRectIntersectsRect(ship.boundingBox, asteroid.boundingBox)) {
NSLog(#"hit");
}
}
}
- (void)countDownToCreateNextAsteroid {
int minTime = 1;
int maxTime = 10;
int randomTime = (arc4random() % (3));
id countdownDelay = [CCDelayTime actionWithDuration:randomTime];
id creationMethod = [CCCallFunc actionWithTarget:self selector:#selector(asteroidCreate)];
id countdownToCreateSeq = [CCSequence actions:countdownDelay, creationMethod, nil];
[self stopAllActions];
[self runAction:countdownToCreateSeq];
}
-(void)asteroidCreate {
CGSize winSize = [[CCDirector sharedDirector] winSize];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:#"asteroids.plist"];
spriteSheet = [CCSpriteBatchNode batchNodeWithFile:#"asteroids.png"];
asteroidAnimFrames = [NSMutableArray array];
for(int i=1; i <= 8; i++) {
[asteroidAnimFrames addObject:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:#"asteroid%d.png", i]]];
}
CCAnimation *moveAsteroidAnim = [CCAnimation animationWithFrames:asteroidAnimFrames delay:0.1f];
CCSprite *asteroid = [CCSprite spriteWithSpriteFrameName:#"asteroid1.png"];
int x = arc4random() % 320;
int y = arc4random() % 480;
asteroid.position = ccp(x, 480);
CCAction *asteroidAction = [CCRepeatForever actionWithAction:[CCAnimate actionWithAnimation:moveAsteroidAnim restoreOriginalFrame:NO]];
[asteroidArray addObject:asteroid];
int q = arc4random() % 320;
int r = arc4random() % 10;
CCAction *moveAction = [CCMoveTo actionWithDuration:r position:ccp(q, -50)];
id asteroidRemove = [CCCallBlock actionWithBlock:^
{
[asteroid removeFromParentAndCleanup:YES];
[asteroidArray removeObject:asteroid];
}];
id asteroidSeq = [CCSequence actions:moveAction, asteroidRemove, nil];
[asteroid runAction:asteroidSeq];
[asteroid runAction:asteroidAction];
[spriteSheet addChild:asteroid];
[self addChild:spriteSheet];
[self countDownToCreateNextAsteroid];
}
-(void)fireLoop:(ccTime)fl {
if(fireArray.count > 0){
for(int i = 0; i < fireArray.count; i++){
CCSprite *tmpFire = [fireArray objectAtIndex:i];
if(tmpFire.position.y < 500){
[tmpFire setPosition:ccp([tmpFire position].x, [tmpFire position].y + fireSpeed)];
}else{
[fireArray removeObjectAtIndex:i];
}
}
} else {
}
}
-(void)fireCreate{
int shootPositionX = [ship position].x;
int shootPositionY = ([ship position].y) + 35;
CCSprite *fire;
fire = [[CCSprite alloc] initWithFile:#"fire.png"];
[fire setPosition:ccp(shootPositionX, shootPositionY)];
[fireArray addObject:fire];
[self addChild:fire];
[fire release];
}
-(void)gameLoop:(ccTime)dt {
int shipPositionX = 41/2;
if([ship position].x > shipPositionX){
[ship setPosition:ccp([ship position].x - speed, [ship position].y)];
}
}
-(void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
//if(point.x <= 160){
// moveRight = NO;
// moveLeft = YES;
//}else{
// moveRight =YES;
// moveLeft = NO;
//}
if(allowedToMove)
[ship setPosition:ccp(point.x, point.y + 76)];
}
}
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
int shipX = [ship position].x;
int shipY = [ship position].y;
if (CGRectContainsPoint(CGRectMake (shipX - 20.5, shipY - 96, 50, 50), point))
{
allowedToMove = true;
}
}
}
-(void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
for(UITouch *t in touches){
CGPoint point = [self convertTouchToNodeSpace:t];
allowedToMove = false;
}
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
#pragma mark GameKit delegate
-(void) achievementViewControllerDidFinish:(GKAchievementViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
-(void) leaderboardViewControllerDidFinish:(GKLeaderboardViewController *)viewController
{
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] dismissModalViewControllerAnimated:YES];
}
#end

Set Time Clicking on Dial

I am working on an alarm app in which I have to show an analogue clock. The functionality is to set time by clicking on the circumference of the circle displayed as the clock dial.
I have succesfully done this too. But the issue comes at 6 O'Clock or 30 min. The angle comes out to be nan for that which makes my smooth clock totally abrupt.
Here is the code.
myPath1 = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(5, 5, 244, 244)];
[myPath1 closePath];
[myPath1 setLineWidth:20];
// Draw a shape Layer with Triangle Path
CAShapeLayer *shapeLayer1 = [CAShapeLayer layer];
shapeLayer1.fillColor = [UIColor clearColor].CGColor;
shapeLayer1.strokeColor = [UIColor clearColor].CGColor;
shapeLayer1.lineWidth = 20;
shapeLayer1.path = myPath1.CGPath;
// Add it to your view
[circleView.layer addSublayer:shapeLayer1];
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:circleView];
if([self containsPointOnStroke:currentPoint onPath:myPath1])
{
[self calculateAngle:currentPoint];
}
}
- (BOOL)containsPointOnStroke:(CGPoint)point onPath:(UIBezierPath *)path
{
CGPathRef cgPath = path.CGPath;
CGPathRef strokedPath = CGPathCreateCopyByStrokingPath(cgPath, NULL, 10,
kCGLineCapRound, kCGLineJoinRound, 1);
BOOL pointIsNearPath = CGPathContainsPoint(strokedPath, NULL, point, NO);
CGPathRelease(strokedPath);
return pointIsNearPath;
}
//---- calculate angle from the point of touch taking center as the reference ----//
- (void) calculateAngle : (CGPoint)currentPoint
{
double distance = sqrt(pow((currentPoint.x - 127), 2.0) + pow((currentPoint.y - 5), 2.0));
float val = ((2 * 14884) - powf((distance), 2)) / (2 * 14884);
float angleVal = acosf(val) * 180/M_PI;
float timeval = angleVal;
//NSLog(#"angleVal : %f timeVal : %.2f", angleVal, timeval);
if (isnan(angleVal))
{
// if the value of the angle val is infinite
if(check == 0)
[hourBtn setTitle:#"06" forState:UIControlStateNormal];
else
[minBtn setTitle:#"30" forState:UIControlStateNormal];
}
else
{
if(check == 0)
{
if (currentPoint.x >= 127)
[hourBtn setTitle:[self getHour:timeval reverseTIme:NO] forState:UIControlStateNormal];
else
[hourBtn setTitle:[self getHour:timeval reverseTIme:YES] forState:UIControlStateNormal];
}
else
{
if (currentPoint.x >= 127)
[minBtn setTitle:[self getMin:timeval reverseTIme:NO] forState:UIControlStateNormal];
else
[minBtn setTitle:[self getMin:timeval reverseTIme:YES] forState:UIControlStateNormal];
}
}
[timeLbl setText:[NSString stringWithFormat:#"%02d:%02d",[hourBtn.titleLabel.text intValue], [minBtn.titleLabel.text intValue]]];
}
//---- get the hour time from the angle ----//
- (NSString *) getHour :(float) angle reverseTIme:(BOOL) reverseCheck
{
int minuteCount = angle * 2;
int quo = minuteCount / 60;
int temp = quo;
if(quo == 0)
quo = 12;
NSString *timeStr = [NSString stringWithFormat:#"%02d", quo];
quo = temp;
if (reverseCheck)
{
int revQuo = 11 - quo;
if(revQuo == 0)
revQuo = 12;
timeStr = [NSString stringWithFormat:#"%02d", revQuo];
}
return timeStr;
}
// get the min time from the angle
- (NSString *) getMin :(float) angle reverseTIme:(BOOL) reverseCheck
{
int minuteCount = angle;
int rem = minuteCount / 6;
NSString *timeStr = [NSString stringWithFormat:#"%02d", rem];
if (reverseCheck)
{
int revRem = 60 - rem;
if(revRem == 60)
revRem = 0;
timeStr = [NSString stringWithFormat:#"%02d", revRem];
}
//NSLog(#"timeStr : %#", timeStr);
return timeStr;
}

Resources