CGContext pdf page aspect fit

前端 未结 5 629
星月不相逢
星月不相逢 2020-12-28 10:07

I am displaying a pdf page on the CGContext using the code

- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
    CGContextSetRGBFillColor(         


        
5条回答
  •  温柔的废话
    2020-12-28 11:08

    Here is my solution, which also handles rotation. Might by useful.

    // Create transformation
    int rotation = CGPDFPageGetRotationAngle(pdfPage);
    CGRect rect = CGPDFPageGetBoxRect(pdfPage, kCGPDFCropBox);
    CGRect rotatedRect = rect;
    CGRectApplyAffineTransform(rotatedRect, CGAffineTransformMakeRotation(M_PI * rotation / 180.0));
    
    CGFloat scale = MIN(self.bounds.size.width / rotatedRect.size.width, self.bounds.size.height / rotatedRect.size.height);
    // Scale
    CGContextConcatCTM(context, CGAffineTransformMakeScale(scale, scale));  
    // Move left bottom cornet to 0, 0
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(rotatedRect.size.width * 0.5, rotatedRect.size.height * 0.5));    
    // Rotate
    CGContextConcatCTM(context, CGAffineTransformMakeRotation(-M_PI * rotation / 180.0));    
    // Move center into 0, 0
    CGContextConcatCTM(context, CGAffineTransformMakeTranslation(-rect.origin.x - rect.size.width * 0.5, -rect.origin.y - rect.size.height * 0.5));
    
    CGContextDrawPDFPage(context, pdfPage);
    

提交回复
热议问题