Pregunta

Estoy creando un CGPath para definir un área en mi juego como este:

CGPathMoveToPoint   ( myPath, NULL, center.x, center.y );
CGPathAddLineToPoint( myPath, NULL,center.x + 100, center.y);
CGPathAddLineToPoint( myPath, NULL, center.x + 100, center.y + 100);
CGPathAddLineToPoint( myPath, NULL, center.x,  center.y + 100);
CGPathCloseSubpath  ( myPath );

Sé que esto es sólo un cuadrado y que sólo podía usar otra CGRect pero el camino que deseo crear en realidad no es en realidad un rectángulo (sólo estoy probando en este momento). Y luego la detección de la zona de contacto simplemente con un:

if (CGPathContainsPoint(myPath, nil, location, YES))

Todo esto funciona bien, el problema es que el CGPath puede estar moviéndose hasta 40 veces por segundo. ¿Cómo puedo mover sin tener que crear una nueva? Sé que puedo hacer algo como esto para "mover" que:

center.y += x;
CGPathRelease(myPath);
myPath = CGPathCreateMutable();
CGPathMoveToPoint   ( myPath, NULL, center.x, center.y );
CGPathAddLineToPoint( myPath, NULL,center.x + 100, center.y);
CGPathAddLineToPoint( myPath, NULL, center.x + 100, center.y + 100);
CGPathAddLineToPoint( myPath, NULL, center.x,  center.y + 100);
CGPathCloseSubpath  ( myPath );

Pero tengo que liberar y crear una nueva ruta hasta 40 veces por segundo, lo que creo que podría tener una penalización de rendimiento; ¿es esto cierto?

Me gustaría ser capaz de moverlo al igual que yo estoy moviendo actualmente algunos CGRects simplemente fijando el origen a un valor diferente, es esto posible con CGPath?

Gracias.

EDIT:. Se me olvidó mencionar que no tengo una GraphicsContext ya que no estoy dibujando en una UIView

¿Fue útil?

Solución

Aplicar una transformación a la CGPath y la prueba en contra de un punto, es equivalente a aplicar el inversa transformación al punto.

Por lo tanto, puede utilizar

CGPoint adjusted_point = CGPointMake(location.x - center.x, location.y - center.y);
if (CGPathContainsPoint(myPath, NULL, adjusted_point, YES)) 

Pero CGPathContainsPoint ya se toma un parámetro CGAffineTransform (que usted ha NULL-ed ella), lo que también puede utilizar

CGAffineTransform transf = CGAffineTransformMakeTranslation(-center.x, -center.y);
if (CGPathContainsPoint(myPath, &transf, location, YES)) 

Si está dibujando, en lugar de cambiar la ruta, puede cambiar la CTM en su código de dibujo directamente.

CGContextSaveGState(c);
CGContextTranslateCTM(c, center.x, center.y);
// draw your path
CGContextRestoreGState(c);

Utilice un CAShapeLayer si necesita rendimiento.

Otros consejos

@ respuesta de KennyTM funcionaba perfectamente para el propósito de la OP, pero la pregunta sigue siendo:

  

¿Cómo puedo mover un CGPath sin crear una nueva?

Bueno, dos líneas de código hicieron el truco para mí:

UIBezierPath* path = [UIBezierPath bezierPathWithCGPath:cgPath];
[path applyTransform:CGAffineTransformMakeTranslation(2.f, 0.f)];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top