Search code examples
core-animationtransformcgpointcatransform3dquartz-core

CATransform3D equivavelent to CGPointApplyAffineTransform and friends


How can I write the CATransform3D equivalent to

CGPoint CGPointApplyAffineTransform(CGPoint point, CGAffineTransform t)
CGSize CGSizeApplyAffineTransform(CGSize size, CGAffineTransform t);
CGRect CGRectApplyAffineTransform(CGRect rect, CGAffineTransform t);

?


Solution

  • This works, but it would ofcourse be a lot better to know what happens inside -[CALayer convertPoint:toLayer:] !

    CGPoint CGPointApplyCATransform3D(CGPoint point, CATransform3D transform, CGPoint anchorPoint, CATransform3D parentSublayerTransform)
    {
    
        static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
        static CALayer *sublayer, *layer;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            sublayer = [CALayer layer];
            layer = [CALayer layer];
            [layer addSublayer:sublayer];
        });
    
        if(pthread_mutex_lock(&mtx))
        {
            [NSException raise:NSInternalInconsistencyException format:@"pthread_mutex_lock failed"];
        }
    
        layer.sublayerTransform = parentSublayerTransform;
        sublayer.transform = transform;
        sublayer.anchorPoint = anchorPoint;
        CGPoint retval = [sublayer convertPoint:point toLayer:layer];
    
        if(pthread_mutex_unlock(&mtx) != 0)
        {
            [NSException raise:NSInternalInconsistencyException format:@"pthread_mutex_unlock failed"];
        } 
    
        return retval;
    }
    

    Simple unit tests https://gist.github.com/hfossli/5130975