I Am facing a problem from last two weeks. Actually I am working on an iPad app. In which I want to do annotation and also make screen recording of that annotations. Annotation part is working fine but it gives problem when I start recording. The problem is that it losts it's smoothness and gives lags during screen recording. For Screen Recording I am using AVAsset Writer. Codes are fine for both Annotation and Screen recording.... But I don't know where is the problem??
My ScreenShot Size is (1050,650)
Should I use Grand Central Dispatch to solve this problem???
Can anybody help me to solve out my problem.....
Plz plz help me....
MY CODE
// For Annotation
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
drawImage.image = nil; //Double click to undo drawing.
return;
}
lastPoint = [touch locationInView:self.view];
lastPoint.y -= 20;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 20;
// UIGraphicsBeginImageContext(canvasView.frame.size);
UIGraphicsBeginImageContext(drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width,drawImage.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 10.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
drawImage.image = nil;
return;
}
if(!mouseSwiped)
{
UIGraphicsBeginImageContext(drawImage.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width,drawImage.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFlush(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
//For Screen Recording
#define FRAME_WIDTH 1024
#define FRAME_HEIGHT 650
#define TIME_SCALE 600
- (UIImage*)screenshot
{
UIGraphicsBeginImageContext(drawImage.frame.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
-(NSURL*) pathToDocumentsDirectory {
NSString* outputPath = [[NSString alloc] initWithFormat:#"%#/%#", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0], #"output.mov"];
outputURL = [[NSURL alloc] initFileURLWithPath:outputPath];
NSFileManager* fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:outputPath]) {
NSError* error;
if ([fileManager removeItemAtPath:outputPath error:&error] == NO) {
NSLog(#"Could not delete old recording file at path: %#", outputPath);
}
}
[outputPath release];
return [outputURL autorelease];
}
-(void) writeSample: (NSTimer*) _timer
{
if (assetWriterInput.readyForMoreMediaData) {
// CMSampleBufferRef sample = nil;
CVReturn cvErr = kCVReturnSuccess;
// get screenshot image!
CGImageRef image = (CGImageRef) [[self screenshot] CGImage];
NSLog (#"made screenshot");
// prepare the pixel buffer
CVPixelBufferRef pixelBuffer = NULL;
CFDataRef imageData= CGDataProviderCopyData(CGImageGetDataProvider(image));
NSLog (#"copied image data");
cvErr = CVPixelBufferCreateWithBytes(kCFAllocatorDefault,
FRAME_WIDTH,
FRAME_HEIGHT,
kCVPixelFormatType_32BGRA,
(void*)CFDataGetBytePtr(imageData),
CGImageGetBytesPerRow(image),
NULL,
NULL,
NULL,
&pixelBuffer);
NSLog (#"CVPixelBufferCreateWithBytes returned %d", cvErr);
// calculate the time
CFAbsoluteTime thisFrameWallClockTime = CFAbsoluteTimeGetCurrent();
CFTimeInterval elapsedTime = thisFrameWallClockTime - firstFrameWallClockTime;
NSLog (#"elapsedTime: %f", elapsedTime);
CMTime presentationTime = CMTimeMake (elapsedTime * TIME_SCALE, TIME_SCALE);
// write the sample
BOOL appended = [assetWriterPixelBufferAdaptor appendPixelBuffer:pixelBuffer withPresentationTime:presentationTime];
if (appended) {
NSLog (#"appended sample at time %lf", CMTimeGetSeconds(presentationTime));
} else {
NSLog (#"failed to append");
[self stopRecording];
}
}
}
-(void) startRecording {
movieURL = [self pathToDocumentsDirectory];
NSLog(#"path=%#",movieURL);
movieError = nil;
[assetWriter release];
assetWriter = [[AVAssetWriter alloc] initWithURL:movieURL
fileType: AVFileTypeQuickTimeMovie
error: &movieError];
[self writer];
// start writing samples to it
NSDate* start = [NSDate date];
frameRate=40.0f;
float processingSeconds = [[NSDate date] timeIntervalSinceDate:start];
delayRemaining = (1.0 / self.frameRate) - processingSeconds;
[assetWriterTimer release];
assetWriterTimer = [NSTimer scheduledTimerWithTimeInterval:delayRemaining > 0.0 ? delayRemaining : 0.01
target:self
selector:#selector (writeSample:)
userInfo:nil
repeats:YES] ;
}
-(void)writer
{
NSDictionary *assetWriterInputSettings = [NSDictionary dictionaryWithObjectsAndKeys:
AVVideoCodecH264, AVVideoCodecKey,
[NSNumber numberWithInt:FRAME_WIDTH], AVVideoWidthKey,
[NSNumber numberWithInt:FRAME_HEIGHT], AVVideoHeightKey,
nil];
assetWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType: AVMediaTypeVideo
outputSettings:assetWriterInputSettings];
assetWriterInput.expectsMediaDataInRealTime = YES;
[assetWriter addInput:assetWriterInput];
[assetWriterPixelBufferAdaptor release];
assetWriterPixelBufferAdaptor = [[AVAssetWriterInputPixelBufferAdaptor alloc]
initWithAssetWriterInput:assetWriterInput
sourcePixelBufferAttributes:nil];
[assetWriter startWriting];
firstFrameWallClockTime = CFAbsoluteTimeGetCurrent();
[assetWriter startSessionAtSourceTime: CMTimeMake(0, TIME_SCALE)];
}
-(void) stopRecording {
[assetWriterTimer invalidate];
assetWriterTimer = nil;
[assetWriter finishWriting];
NSLog (#"finished writing");
}
Simplest approach is to try lower frame rates.
Related
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.
How to Draw a straight line in iOS irrespective of how user draws it.
I want the line to be of the length of number of pixels user drags his finger.
But it needs to be either vertical or horizontal based on whether user slides his finger from left to right of the screen or top to bottom of the screen.
Lines should not be slanting or any other shape. It needs to be straight.
I have gone through articles which says "Open GL" is the only way.
I have tried coding it myself but when I change the direction from vertical to horizontal or vice versa, I get some extra line or gap between where horizontal line ends and where vertical line starts:
In header file:
#interface ViewController : UIViewController
{
BOOL mouseSwiped;
CGPoint lastPoint;
CGPoint previousPoint;
UIBezierPath *currentPath;
CGFloat lastPointY;
CGFloat lastPointX;
BOOL xchanging;
BOOL ychanging;
NSMutableArray *arrayTouch;
}
#property (weak, nonatomic) IBOutlet UIImageView *drawImage;
#property UIBezierPath *currentPath;
#end
In implementation file:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2) {
drawImage.image = nil;
[arrayTouch removeAllObjects];
return;
}
lastPoint = [touch locationInView:self.view];
[arrayTouch addObject:touch];
lastPointY = lastPoint.y;
lastPointX = lastPoint.x;
lastPoint.y -= 1;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self.view];
currentPoint.y -= 1;
int currentPointXVal = currentPoint.x;
int currentPointYVal = currentPoint.y;
int lastPointXVal = lastPoint.x;
int lastPointYVal = lastPoint.y;
int diffX = abs(currentPointXVal - lastPointXVal);
int diffY = abs(currentPointYVal - lastPointYVal);
if(currentPoint.x > lastPoint.x && diffX > diffY)
{
if(ychanging == YES)
{
lastPointY = currentPoint.y;
lastPointX = currentPoint.x;
ychanging = NO;
}
xchanging = YES;
NSLog(#"x increasing");
NSLog(#"currentPoint: %#",NSStringFromCGPoint(currentPoint));
NSLog(#"lastPoint: %#",NSStringFromCGPoint(lastPoint));
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPointY);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, lastPointY);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
if(currentPoint.y > lastPoint.y && diffY > diffX)
{
if(xchanging == YES)
{
lastPointY = currentPoint.y;
lastPointX = currentPoint.x;
xchanging = NO;
}
ychanging = YES;
NSLog(#"y increasing");
NSLog(#"currentPoint: %#",NSStringFromCGPoint(currentPoint));
NSLog(#"lastPoint: %#",NSStringFromCGPoint(lastPoint));
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPointX, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPointX, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
if(currentPoint.x < lastPoint.x && diffX > diffY)
{
if(ychanging == YES)
{
lastPointY = currentPoint.y;
lastPointX = currentPoint.x;
ychanging = NO;
}
xchanging = YES;
NSLog(#"x decreasing");
NSLog(#"currentPoint: %#",NSStringFromCGPoint(currentPoint));
NSLog(#"lastPoint: %#",NSStringFromCGPoint(lastPoint));
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPointY);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, lastPointY);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
if(currentPoint.y < lastPoint.y && diffY > diffX)
{
if(xchanging == YES)
{
lastPointY = currentPoint.y;
lastPointX = currentPoint.x;
xchanging = NO;
}
ychanging = YES;
NSLog(#"y decreasing");
NSLog(#"currentPoint: %#",NSStringFromCGPoint(currentPoint));
NSLog(#"lastPoint: %#",NSStringFromCGPoint(lastPoint));
UIGraphicsBeginImageContext(self.view.frame.size);
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPointX, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPointX, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
lastPoint = currentPoint;
}
Is there any way I can do it without Open GL?
Sure - You can do this, just take away the slope from the line:
#implementation LineDrawingView
{
CGPoint touchStart;
CGPoint touchCurrent;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
touchStart = (CGPoint) { -1, -1 };
touchCurrent = (CGPoint) { -1, -1 };
}
return self;
}
- (void)drawRect:(CGRect)rect
{
if (touchStart.x != -1)
{
// calculate the line rotation
enum { horizontal, vertical } lineRot = horizontal;
if (touchStart.y == touchCurrent.y)
{
// straight line
lineRot = horizontal;
}
else
{
// calculate the slope
double slope = fabs((touchCurrent.y - touchStart.y) / (touchCurrent.x - touchStart.x));
if (slope > 1)
lineRot = vertical;
}
// draw the actual line
CGPoint lineEndPoint = { };
if (lineRot == horizontal)
lineEndPoint = (CGPoint) { touchCurrent.x, touchStart.y }; // horizontal line
else
lineEndPoint = (CGPoint) { touchStart.x, touchCurrent.y }; // vertical line
// actually draw the line
[[UIColor redColor] setStroke];
UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:touchStart];
[path addLineToPoint:lineEndPoint];
[path stroke];
}
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
touchStart = [[touches anyObject] locationInView:self];
touchCurrent = touchStart;
[self setNeedsDisplay];
}
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
touchCurrent = [[touches anyObject] locationInView:self];
[self setNeedsDisplay];
}
-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
touchStart = touchCurrent = (CGPoint) { -1, -1 };
[self setNeedsDisplay];
}
#end
You can extend this to use an array of lines if you'd like, this is just a simple explanation.
So I was just coding along, then Xcode just started going whack when I hit build and gave me all these error that I have never had before
Here is the file:
import
#import <OpenGLES/EAGLDrawable.h>
#import "EAGLView.h"
#define USE_DEPTH_BUFFER 0
// A class extension to declare private methods #interface EAGLView ()
#property (nonatomic, retain) EAGLContext *context; #property (nonatomic, assign) NSTimer *animationTimer;
- (BOOL) createFramebuffer;
- (void) destroyFramebuffer;
- (void) updateScene:(float)delta;
- (void) renderScene;
#end
#implementation EAGLView
#synthesize context; #synthesize animationTimer; #synthesize animationInterval;
// You must implement this method
+ (Class)layerClass {
return [CAEAGLLayer class]; }
//The GL view is stored in the nib file. When it's unarchived it's sent -initWithCoder:
- (id)initWithCoder:(NSCoder*)coder {
if ((self = [super initWithCoder:coder])) {
// 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;
CGRect rect = [[UIScreen mainScreen] bounds];
// Set up OpenGL projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrthof(0,
rect.size.width, 0, rect.size.height, -1, 1);
glMatrixMode(GL_MODELVIEW); glViewport(0, 0, rect.size.width,
rect.size.height);
// Initialize OpenGL states glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_DEPTH_TEST);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND_SRC);
glEnableClientState(GL_VERTEX_ARRAY); glClearColor(0.0f, 0.0f,
0.0f, 1.0f);
// init [self initGame];
UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
accel.delegate = self;
accel.updateInterval = 1.0f / 60.0f;
//[sharedSoundManager playMusicWithKey:#"song" timesToRepeat:-1];
}
return self; }
-(void) initGame{
//SET GAME STATE
//0 = Menu
//1 = Gameplay
//2 = death screen
gameState = 0;
player = [[Circle alloc] init];
score = 0;
scoreString = [NSString alloc];
scoreAdder = 1;
//[self setupScore];
menu = [[Image alloc] initWithImage:[UIImage imageNamed:#"loadImage.png"]];
bk = [[Image alloc] initWithImage:[UIImage imageNamed:#"bk.png"]];
squared = [[Image alloc] initWithImage:[UIImage imageNamed:#"squared.png"]];
gameRunning = TRUE;
gameState = 0;
squares = [[Squares alloc] init];
[squares addSquare: CGPointMake(100, 100) : 0];
//font = [[AngelCodeFont alloc]initWithFontImageNamed:#"font1.png" controlFile:#"font1.fnt"
scale: 0.0f filter: nil];
// Init sound sharedSoundManager = [SingletonSoundManager sharedSoundManager]; [sharedSoundManager loadSoundWithKey:#"menu"
fileName:#"Menu" fileExt:#"mp3" frequency: 22050];
[sharedSoundManager loadBackgroundMusicWithKey:#"music" fileName:#"bkmusic" fileExt:#"aif"];
menuMusicVariable = 1;
gameMusicVariable = 1;
}
-(void) setRunning: (bool) boolean{
gameRunning = boolean; }
-(void) runContinueCountdown{
if(gameRunning == NO){
int timer = 300;
int countdownNum;
timer --;
if(timer <= 300){
if(timer > 200){
countdownNum = 3;
}
if(timer <= 200){
if(timer > 100){
countdownNum = 2;
}
}
if(timer <= 100){
if(timer >= 1){
countdownNum = 1;
}
}
if(timer == 0 && countdownNum == 1){
[self setRunning: YES];
}
} }
- (void) mainGameLoop { CFTimeInterval time; float delta; time = CFAbsoluteTimeGetCurrent(); delta = (time - lastTime);
[self updateScene:delta]; [self renderScene]; lastTime = time;
}
- (void)updateScene:(float)delta { // Update Game Logic
if(gameRunning){
if(gameState == 0){
//MENU
if(menuMusicVariable == 1){
[sharedSoundManager stopPlayingMusic];
[sharedSoundManager playSoundWithKey:#"Menu" gain:10 pitch:10 location:Vector2fMake(0, 0) shouldLoop: TRUE];
menuMusicVariable = 0;
}
[scoreLabel setHidden: YES];
} else if(gameState == 1){
//GAMEPLAY
if(gameMusicVariable == 1){
[sharedSoundManager stopPlayingMusic];
[sharedSoundManager playMusicWithKey: #"music" timesToRepeat: -1];
gameMusicVariable = 0;
}
[scoreLabel setHidden: NO];
//game is running
if([player getAlive] == true){
score = score + scoreAdder;
} else {
score = score;
}
[player move];
[self checkSquareToCircleCollisions];
[self checkSquareToSquareCollisions];
[squares update];
} else if(gameState == 2){
//DEATH SCREEN
[sharedSoundManager stopPlayingMusic];
[scoreLabel setBounds: CGRectMake(100, 100 , 100, 40)];
}
} else {
//game is puased
} }
- (void)renderScene {
// Make sure we are renderin to the frame buffer
[EAGLContext setCurrentContext:context];
glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
// Clear the color buffer with the glClearColor which has been set glClear(GL_COLOR_BUFFER_BIT); //Render the game Scene
if(gameState == 0){
//MENU
[menu renderAtPoint: CGPointMake(0, 0) centerOfImage: NO];
} else if(gameState == 1){
//GAMEPLAY
[bk renderAtPoint: CGPointMake(0, 0) centerOfImage: NO];
[self drawScore];
[player draw];
[squares render];
//[font drawStringAt: CGPointMake(150, 100) text:#"HELLO FONTS"];
} else if(gameState ==2){
//DEATH SCREEN
[squared renderAtPoint: CGPointMake(0, 0) centerOfImage: NO];
} // Switch the render buffer and framebuffer so our scene is displayed on the screen
glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
[context presentRenderbuffer:GL_RENDERBUFFER_OES]; }
- (void)layoutSubviews {
[EAGLContext setCurrentContext:context];
[self destroyFramebuffer];
[self createFramebuffer];
[self renderScene]; }
- (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;
} }
- (void)startAnimation {
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self
selector:#selector(mainGameLoop) userInfo:nil repeats:YES]; }
- (void)stopAnimation {
self.animationTimer = nil; }
- (void)setAnimationTimer:(NSTimer *)newTimer {
[animationTimer invalidate];
animationTimer = newTimer; }
- (void)setAnimationInterval:(NSTimeInterval)interval {
animationInterval = interval;
if (animationTimer) {
[self stopAnimation];
[self startAnimation];
} }
-(void) setupScore{
scoreLabel = [NSString stringWithFormat:#"%d", score];
scoreLabel.frame = CGRectMake(262, 250, 100, 40);
[scoreLabel setText: scoreString];
//normally you'll want a transparent background for your label
scoreLabel.backgroundColor = [UIColor clearColor];
//you can use non-standard fonts
[scoreLabel setFont:[UIFont fontWithName:#"TimesNewRoman" size: 1.0f]];
//change the label's text color
scoreLabel.textColor = [UIColor whiteColor];
//add it to your view
scoreLabel.transform = CGAffineTransformMakeRotation(89.53);
[self addSubview:scoreLabel]; }
-(void) resetScore {
score = 0;
scoreLabel.textColor = [UIColor blackColor];
[scoreLabel release]; }
-(void)drawScore{
[scoreLabel setText: scoreString]; }
-(void) checkSquareToCircleCollisions{
NSMutableArray *array = [squares getSquares];
for(int i = 0; i < [squares getCount]; i++){
Square *s = [array objectAtIndex: i];
CGRect rect1 = [player getRect];
CGRect rect2 = [s getRect];
if (CGRectIntersectsRect(rect1, rect2)){
player.alive = NO;
gameState = 2;
}
} }
-(void) checkSquareToSquareCollisions{
NSMutableArray *array = [squares getSquares];
for(int i = 0; i < [squares getCount]; i++){
Square *s = [array objectAtIndex: 0];
Square *ss = [array objectAtIndex: i];
CGRect rect1 = [s getRect];
CGRect rect2 = [ss getRect];
if (CGRectIntersectsRect(rect1, rect2)) {
[s setDirection: [s getXDir] * -1 : [s getYDir] * -1];
[ss setDirection: [ss getXDir] * -1 : [ss getYDir] * -1];
}
} }
-(void) spawnSquares {
// FINISH METHOD
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(gameState == 0){
//MENU
UITouch *touch = [[event allTouches] anyObject];
gameState = 1;
//[self initGame];
} else if(gameState == 1){
//GAMEPLAY
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:touch.view];
touchPos.y = 480 - touchPos.y;
[player setPos: touchPos];
} else if(gameState == 2){
//DEATH SCREEN
UITouch *touch = [[event allTouches] anyObject];
gameState = 0;
//[self resetScore];
[self initGame];
} }
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(gameState == 0){
//MENU
UITouch *touch = [[event allTouches] anyObject];
//[self initGame];
} else if(gameState == 1){
//GAMEPLAY
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchPos = [touch locationInView:touch.view];
touchPos.y = 480 - touchPos.y;
[player setPos: touchPos];
} else if(gameState == 2){
//DEATH SCREEN
UITouch *touch = [[event allTouches] anyObject];
}}
- (void)accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration {
point.y = acceleration.y * 10;
point.x = acceleration.x * 10;
CGPoint pos = [player getPos];
pos = CGPointMake(pos.x + point.x, pos.y + point.y);
[player setPos: pos];
//Right - MAY HAVE TO CHANGE
if(pos.x < 0){
pos = CGPointMake(320, pos.y);
}
//left
if(pos.x < 320){
pos = CGPointMake(0, pos.y);
}
//Top
if(pos.y < 0){
pos = CGPointMake(pos.x, 460);
}
//Bottom
if(pos.x < 460){
pos = CGPointMake(pos.x, 0);
}
}
- (void)dealloc {
[self stopAnimation];
if ([EAGLContext currentContext] == context) {
[EAGLContext setCurrentContext:nil];
}
[context release];
[player release];
[menu release];
[sharedSoundManager release];
[bk release];
[squared release];
[squares release];
[scoreLabel release];
[scoreString release];
[super dealloc]; }
#end // here it says: excepted } and also its excepting #end
You are missing a brace in the runContinueCountdown at the end of the second if statement.
if(timer <= 300){
if(timer > 200){
countdownNum = 3;
}
Add a brace to the end of this if statement
I need to make an UIImageView, on a scroll View, active for touching.
is a little UiimageView 100x50 were people can make the signature.
I am using the same code and it works, but with scroll view it doesn't.
I looked around, but I could not find a code for that.
.h
UIImageView *drawImage;
#property (nonatomic, retain) IBOutlet UIImageView *drawImage;
.m
#synthesize drawImage;
- (void)viewDidLoad {
[scrollView setScrollEnabled:YES];
[scrollView setContentSize:CGSizeMake(320,1540)];
if ([MFMailComposeViewController canSendMail])
button.enabled = YES;
drawImage.userInteractionEnabled = YES;
UITapGestureRecognizer *gestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(touchesBegan:)];
gestureRec.numberOfTouchesRequired = 1;
gestureRec.numberOfTapsRequired = 1;
[drawImage addGestureRecognizer:gestureRec];
[gestureRec release];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addTarget:self action:#selector(printItem) forControlEvents:UIControlEventTouchDown];
btn.frame = CGRectMake(75, 0, 44, 44);
[btn setImage:[UIImage imageNamed:#"print.png"] forState:UIControlStateNormal];
[self.view addSubview:btn];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 3) {
drawImage.image = nil;
return;
}
lastPoint = [touch locationInView:drawImage];
// lastPoint.y -=20;// only if signature goes bottom of the screen
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:drawImage];
currentPoint.y -=5; // only if signature goes bottom of the screen
UIGraphicsBeginImageContext(drawImage.frame.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextSetLineCap(currentContext, kCGLineCapRound);
CGContextSetLineWidth(currentContext, 2.0);
CGContextSetRGBStrokeColor(currentContext, 0.0, 0.0, 0.0, 1.0);
CGContextBeginPath(currentContext);
CGContextMoveToPoint(currentContext, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(currentContext, currentPoint.x, currentPoint.y);
CGContextStrokePath(currentContext);
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 3) {
drawImage.image = nil;
return;
}
if(!mouseSwiped) {
UIGraphicsBeginImageContext(drawImage.frame.size);
CGContextRef currentContext = UIGraphicsGetCurrentContext();
[drawImage.image drawInRect:CGRectMake(0, 0, drawImage.frame.size.width, drawImage.frame.size.height)];
CGContextSetLineCap(currentContext, kCGLineCapRound);
CGContextSetLineWidth(currentContext, 3.0);
CGContextSetRGBStrokeColor(currentContext, 1.0, 1.0, 2.0, 2.0);
CGContextMoveToPoint(currentContext, lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(currentContext, lastPoint.x, lastPoint.y);
CGContextStrokePath(currentContext);
drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
I tried the NSZombieEnabled and I get a SIGABRIT on the UITouch line on touchesBegan
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 3) {
drawImage.image = nil;
return;
}
lastPoint = [touch locationInView:drawImage];
// lastPoint.y -=20;// only if signature goes bottom of the screen
}
and a SIGABRIT here, in the int main(int argc, char *argv[]) line
#import <UIKit/UIKit.h>
int main(int argc, char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int retVal = UIApplicationMain(argc, argv, nil, nil);
[pool release];
return retVal;
}
I still get the error like before:
2011-05-10 22:14:22.509 anamnesiprova[90427:207] -[UITapGestureRecognizer anyObject]: unrecognized selector sent to instance 0x6bd5ba0
2011-05-10 22:14:22.512 anamnesiprova[90427:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITapGestureRecognizer anyObject]: unrecognized selector sent to instance 0x6bd5ba0'
I think you have to set userInteractionEnabled of your UIImageView to YES.
Another idea would be to add a GestureRecognizer to your imageView, for the beginning a simple one:
UITapGestureRecognizer *gestureRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(myMethodToBeCalled)];
gestureRec.numberOfTouchesRequired = 1;
gestureRec.numberOfTapsRequired = 1;
[myImageView addGestureRecognizer:gestureRec];
[gestureRec release];
I am having an image on my view and i am painting on the image with colors like the code below:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
mouseSwiped = NO;
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
//imageDraw.image = nil;
return;
}
else
{
}
lastPoint = [touch locationInView:imageDraw];
lastPoint.y -= 5;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:mView];
currentPoint.y -= 5;
UIGraphicsBeginImageContext(imageDraw.frame.size);
[imageDraw.image drawInRect:CGRectMake(0, 0, imageDraw.frame.size.width, imageDraw.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
//CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 0.5);
DrawAppDelegate *appDelegate=(DrawAppDelegate*)[ [UIApplication sharedApplication] delegate];
UIColor *clr = appDelegate.txtColor;
[clr setStroke];
CGContextBeginPath(UIGraphicsGetCurrentContext());
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
imageDraw.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
lastPoint = currentPoint;
mouseMoved++;
if (mouseMoved == 10)
{
mouseMoved = 0;
}
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
DrawAppDelegate *appDelegate=(DrawAppDelegate*)[ [UIApplication sharedApplication] delegate];
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 2)
{
//imageDraw.image = nil;
return;
}
else
{
}
if(!mouseSwiped)
{
UIGraphicsBeginImageContext(imageDraw.frame.size);
[imageDraw.image drawInRect:CGRectMake(0, 0, imageDraw.frame.size.width, imageDraw.frame.size.height)];
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
UIColor *clr = appDelegate.txtColor;
[clr setStroke];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
CGContextStrokePath(UIGraphicsGetCurrentContext());
CGContextFlush(UIGraphicsGetCurrentContext());
imageDraw.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
}
-(void)drawText
{
/*TextViewController *viewController = [[TextViewController alloc]init];
[self.navigationController pushViewController:viewController animated:YES];
[viewController release];
*/
colorWheel = [[ColorPickerImageView alloc] initWithFrame:CGRectMake(20,20,300,340)];
[colorWheel setImage:[UIImage imageNamed:#"colorWheel1.png"]];
[colorWheel setUserInteractionEnabled:YES];
colorWheel.backgroundColor = [UIColor clearColor];
colorWheel.pickedColorDelegate = self;
[mView addSubview:colorWheel];
[self animateColorWheelToShow:YES duration:0.3];
}
- (void) pickedColor:(UIColor*)color
{
//mView.backgroundColor= color;
DrawAppDelegate *appDelegate=(DrawAppDelegate*)[ [UIApplication sharedApplication] delegate];
[self animateColorWheelToShow:NO duration:0.3];
appDelegate.txtColor = color;
//[self setNeedsDisplayInRect:CGRectMake(0, 0, 320, 480)];
[mView setNeedsDisplay];
}
Now I want to erase some painted color on the image.Can anyone suggest me How I can I do any ideas pls with some sample code.
Anyone's help will be deeply appreciate.
Thanks to all,
Monish.
The answer is in the order of the lines. To clear and erase use clearColor.
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
self.previousPoint1 = [touch previousLocationInView:self.imageView];
self.previousPoint2 = [touch previousLocationInView:self.imageView];
self.currentPoint = [touch locationInView:self.imageView];
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
self.previousPoint2 = self.previousPoint1;
self.previousPoint1 = [touch previousLocationInView:self.imageView];
self.currentPoint = [touch locationInView:self.imageView];
// calculate mid point
CGPoint mid1 = midPoint(self.previousPoint1, self.previousPoint2);
CGPoint mid2 = midPoint(self.currentPoint, self.previousPoint1);
UIGraphicsBeginImageContext(self.imageView.frame.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self.imageView.image drawInRect:CGRectMake(0, 0, self.imageView.frame.size.width, self.imageView.frame.size.height)];
if (self.segmentedControl.selectedSegmentIndex == 11) {
CGContextSetBlendMode(context, kCGBlendModeClear);
} else {
CGContextSetBlendMode(context, kCGBlendModeNormal);
}
CGContextMoveToPoint(context, mid1.x, mid1.y);
// Use QuadCurve is the key
CGContextAddQuadCurveToPoint(context, self.previousPoint1.x, self.previousPoint1.y, mid2.x, mid2.y);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineWidth(context, 20.0);
[self.color setStroke];
CGContextStrokePath(context);
self.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
- (NSArray *)colors {
return #[[UIColor colorWithRed:249/255.0 green:195/255.0 blue:207/255.0 alpha:1.0],
[UIColor colorWithRed:225/255.0 green:57 /255.0 blue:156/255.0 alpha:1.0],
[UIColor colorWithRed:97 /255.0 green:48 /255.0 blue:138/255.0 alpha:1.0],
[UIColor colorWithRed:255/255.0 green:199/255.0 blue:69 /255.0 alpha:1.0],
[UIColor colorWithRed:245/255.0 green:125/255.0 blue:55 /255.0 alpha:1.0],
[UIColor colorWithRed:194/255.0 green:25 /255.0 blue:48 /255.0 alpha:1.0],
[UIColor colorWithRed:135/255.0 green:214/255.0 blue:242/255.0 alpha:1.0],
[UIColor colorWithRed:23 /255.0 green:185/255.0 blue:181/255.0 alpha:1.0],
[UIColor colorWithRed:0 /255.0 green:77 /255.0 blue:119/255.0 alpha:1.0],
[UIColor colorWithRed:0 /255.0 green:104/255.0 blue:61 /255.0 alpha:1.0],
[UIColor colorWithRed:0 /255.0 green:163/255.0 blue:89 /255.0 alpha:1.0],
[UIColor clearColor],
[UIColor clearColor],
[UIColor clearColor],
[UIColor clearColor]
];
}
do like this..
for selecting somepart of yor image for erase
give this code,,
UIColor *selectedColor;
self.selectedColor=[UIColor whiteColor];
select that particular part with white color..
Thank u..