2012-04-19 7 views
7

Estoy creando una aplicación de pintura y quiero saber cómo implementar la herramienta de borrador. No quiero que mi herramienta de borrador pinte color blanco porque quiero permitir a los usuarios cambiar el color de fondo. Y también, ¿es posible establecer la dureza del pincel? Si es así, por favor dígame cómo.Haciendo una herramienta de borrador para una aplicación de pintura en iOS

Gracias

Esto es lo que he hecho hasta ahora:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    lastPoint = [touch locationInView:self.view]; 
} 

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint currentPoint = [touch locationInView:self.view]; 
    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(), 10); 
    CGContextBeginPath(UIGraphicsGetCurrentContext()); 
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0); 
    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]; 
CGPoint currentPoint = [touch locationInView:self.view]; 
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(), 10); 
CGContextBeginPath(UIGraphicsGetCurrentContext()); 
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0.0, 0.0, 0.0, 1.0); 
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y); 
CGContextStrokePath(UIGraphicsGetCurrentContext()); 
drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

lastPoint = currentPoint; 
} 
- (IBAction)clear:(id)sender { 
drawImage.image = nil; 
} 
+0

Esta es una pregunta interesante, pero creo que podría hacer que sea mucho más clara. Cuéntanos sobre lo que tienes hasta ahora; quizás incluya algún código. – jtbandes

+0

@jtbandes He agregado el código –

+0

por favor, mira este enlace y mira mi respuesta http://stackoverflow.com/questions/3863931/want-to-add-manual-erasing-option-in-ipad-painting- aplicación por cuarzo/12797513 # 12797513 –

Respuesta

13

autorización aquí es lo que hice para la herramienta de borrador:
que añadir esta línea de código:
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear);

Así que el código será algo así:

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
UITouch *touch = [touches anyObject]; 
CGPoint currentPoint = [touch locationInView:self.view]; 
UIGraphicsBeginImageContext(self.view.frame.size); 
[drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 

// I add this 
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear); 

CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); 
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), sizeSlider.value); 
CGContextBeginPath(UIGraphicsGetCurrentContext()); 
CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeClear); 
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y); 
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y); 

CGContextStrokePath(UIGraphicsGetCurrentContext()); 
drawImage.image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
lastPoint = currentPoint; 
} 
+3

Muchas gracias. Funciona increíble. He estado buscando esto desde hace mucho tiempo. –

+0

Muchas gracias :) – iRiziya

4

tengo hacer uso de la pintura y está disponible en iTunes "Fácil Doodle" de la aplicación. No hay una lógica especial para el borrador. acaba de obtener el valor RGB de la imagen de fondo y pasarlo en

CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(),R value,G value,B value, 1.0); 

según la imagen de fondo seleccionada a.

+0

@mat hi .. si creamos UIView personalizado para pintura, ¿qué podemos pintar sin drawrect mehod? – Hitarth

+0

Probablemente usted quería preguntarle a Rock, pero no lo creo, si tiene una UIView personalizada, necesita llamar a setNeedsDiplay para dibujar la vista cada vez que quiera modificarla. De lo contrario, eche un vistazo a mi antigua [respuesta similar] (http://stackoverflow.com/a/10667557/251513). – Mat

+1

Esta no es la respuesta correcta. La respuesta correcta es la siguiente con más votos al alza. Apple tiene una función de borrador incorporada que es una línea de código. Esta respuesta ni siquiera borra, simplemente agrega más "pintura" a la imagen, solo el mismo color que el píxel debajo de ella (imagen de fondo). Realmente no se borra (especialmente si la imagen de fondo cambia) y mucha más información. –

1

Ok por lo He estado buscando una solución sobre cómo crear un borrador por una semana, tuve que cambiar la forma en que lo veía porque, sin importar cuántas veces intentara borrar algo, también borraba la imagen de fondo.

Sin embargo, al final encontré una solución que me satisfizo (donde pude borrar la pintura y todavía no se ha alterado o borrado la imagen de fondo) y espero que ayude a los demás. así que aquí va ...

1) Crear 2 imageviews en el UIView 2) Ajuste ambos imageviews la imagen de fondo que usted quiere que sea en ... 3) que crea un control segmentado para determinar si el usuario desea borrar 4) añade la siguiente función cuando se selecciona el control segmentado ..

func drawLineForRubber(fromPoint: CGPoint, toPoint: CGPoint) { 

    // 1 
    UIGraphicsBeginImageContext(view.frame.size) 
    let context = UIGraphicsGetCurrentContext() 
    mainImageView.image?.drawInRect(CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)) 

    // 2 
    CGContextMoveToPoint(context, fromPoint.x, fromPoint.y) 
    CGContextAddLineToPoint(context, toPoint.x, toPoint.y) 

    // 3 
    CGContextSetBlendMode(context, CGBlendMode.Clear) 
    CGContextSetLineCap(context, CGLineCap.Round) 
    CGContextSetLineWidth(context, 10.0) 
    //this line is very important as it paints the screen clear 
    CGContextSetRGBStrokeColor(context, red, green, blue, 0.0) 
    CGContextSetBlendMode(context, CGBlendMode.Clear) 

    // 4 
    CGContextStrokePath(context) 

    // 5 
    mainImageView.image = UIGraphicsGetImageFromCurrentImageContext() 
    mainImageView.alpha = opacity 
    UIGraphicsEndImageContext() 

} 

Como se puede ver que hay una línea de ahí que establece el CGContextSetRGBStrokeColor con el valor de 0,0, esto es causa importante cuando el usuario está borrando la pintura, está borrando la pintura de la vista superior de la imagen junto con la pintura con un color transparente r. Sin embargo, dado que tiene otra vista de imagen debajo, la percepción es que parece borrarse sin afectar la imagen de fondo.

Por el contrario, se borra pero la imagen de atrás, hace que parezca que no lo ha sido. Cuando desee exportar la imagen (puede hacerlo de varias maneras, pero fui con la siguiente) que pintó con la imagen de fondo, simplemente combine ambas vistas de imagen, ya que la primera vista de la imagen tendrá pintada la pintura y el 2nd imageview tendrá la imagen de fondo original que deseaba.

func share() { 

    let layer = UIApplication.sharedApplication().keyWindow!.layer 
    let scale = UIScreen.mainScreen().scale 
    UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); // reconsider size property for your screenshot 

    layer.renderInContext(UIGraphicsGetCurrentContext()!) 
    let screenshot = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 


    UIGraphicsBeginImageContext(mainImageView.bounds.size) 
    mainImageView.image?.drawInRect(CGRect(x: 0, y: 0, 
     width: mainImageView.frame.size.width, height: mainImageView.frame.size.height)) 

    UIGraphicsEndImageContext() 

    let activity = UIActivityViewController(activityItems: [screenshot], applicationActivities: nil) 
    presentViewController(activity, animated: true, completion: nil) 
} 

Esperanza esto ayuda a otros en el camino .. hombre me tomó las edades para conseguir mi cabeza alrededor de ella =)

Cuestiones relacionadas