newXPosition = (x * cos(degree)) - (y * sin(degree))
newYPosition = (x * sin(degree)) + (y * cos(degree))
Suppose i have a line from (100, 100) to (150, 150), I want to rotate it from (100, 100).
Now we need to change the arbitrary point from (0, 0) to (100, 100). how to do?
First find out the length of the line then apply the theta, calculate the new poing and add the x and y position with the new x and y position.
(100, 100) and (150, 150)
length is (50, 50)
now i need to rotate the line theta angle.
newX = (50 * cos(degree)) + (50 * sin(degree))
newY = (50 * sin(degree)) + (50 * cos(degree))
newX = newX + 100;
newY = newY + 100;
//
// STBView.h
// STBLineRotation
//
// Created by Stalin on 1/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface STBView : UIView
{
float newX, newY, newX1, newY1;
float radian;
}
@end
//
// STBView.m
// STBLineRotation
//
// Created by Stalin on 1/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "STBView.h"
@implementation STBView
- (id)initWithCoder:(NSCoder *)aDecoder;
{
self = [super initWithCoder:aDecoder];
if (self) {
// Initialization code
newX = 100.0f;
newY = 100.0f;
newX1 = 150.0f;
newY1 = 150.0f;
radian = 0.5;
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef c = UIGraphicsGetCurrentContext();
CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
float degree = (radian * M_PI) / 180;
NSLog(@"%f %f %f %f", newX, newY, newX1, newY1);
float x, y;
x = newX1;
y = newY1;
x -= newX;
y -= newY;
newX1 = (x * cos(degree)) - (y * sin(degree));
newY1 = (x * sin(degree)) + (y * cos(degree));
newX1 += newX;
newY1 += newY;
NSLog(@"%f %f %f %f", newX, newY, newX1, newY1);
CGContextSetStrokeColor(c, red);
CGContextBeginPath(c);
CGContextMoveToPoint(c, newX, newY);
CGContextAddLineToPoint(c, newX1, newY1);
CGContextStrokePath(c);
}
@end
//
// ViewController.m
// STBLineRotation
//
// Created by Stalin on 1/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "ViewController.h"
@implementation ViewController
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1.0/30.0 target:self selector:@selector(rotateLine:) userInfo:nil repeats:YES];
// Do any additional setup after loading the view, typically from a nib.
}
-(void) rotateLine:(id) sender
{
[self.view setNeedsDisplay];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
@end
Download the object C code for line rotation
No comments:
Post a Comment