3

I'm using UIPrintPageRenderer sub-class to print html content on a pdf. How can i add a horizontal line on my printed content (both on header and footer)?

CGContextAddLineToPoint doesn't seem to work in UIPrintPageRenderer methods. Specifically those used to draw header and footer. NSString's drawAtPoint is working perfectly.

Here's what i've tried so far:

- (void)drawHeaderForPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)headerRect {
    ...

    // Attempt 1 (Doesn't work!)
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1);
    CGContextSetRGBStrokeColor(context, 1.0f, 1.0f, 1.0f, 1);
    CGContextMoveToPoint(context, 10.0, 20.0);
    CGContextAddLineToPoint(context, 310.0, 20.0);

    // Attempt 2 (Doesn't work!)
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetRGBFillColor(context, 1.0f, 1.0f, 1.0f, 1);
    CGContextSetRGBStrokeColor(context, 1.0f, 1.0f, 1.0f, 1);

    CGContextTranslateCTM(context, 0, headerRect.size.height);
    CGContextScaleCTM(context, 1, -1);

    CGContextMoveToPoint(context, 10.0, 20.0);
    CGContextAddLineToPoint(context, 310.0, 20.0);
}
4

3 回答 3

1

在 Core Graphics 中,逻辑图形元素被添加到上下文中,然后被绘制。我看到您使用例如添加到上下文的路径CGContextAddLineToPoint(context, 310.0, 20.0);

这会在内存中创建路径,但要将其合成到屏幕上,您需要填充或描边上下文的路径。尝试CGContextStrokePath(context);在实际添加之后添加路径。

于 2013-01-30T22:20:44.747 回答
1

和普通的绘图一样

- (void)drawHeaderForPageAtIndex:(NSInteger)pageIndex inRect:(CGRect)headerRect {

    CGContextRef context = UIGraphicsGetCurrentContext();

    CContextMoveToPoint(context, CGRectGetMinX(headerRect), 70);
    CGContextAddLineToPoint(context, CGRectGetMaxX(headerRect), 70);

    CGFloat grayScale = 0.5f;
    CGContextSetRGBStrokeColor(context, grayScale, grayScale, grayScale, 1);

    CGContextStrokePath(context);
}

不要忘记CGStrokePath(...)

于 2015-06-01T07:01:58.873 回答
0

所以,现在我已经应用了一个替代解决方案。我仍然很想知道如何使用 CGContext 来做到这一点(无需加载图像)。这是我的解决方案:

// Draw horizontal ruler in the header
UIImage *horizontalRule = [UIImage imageNamed:@"HorizontalRule.png"];
horizontalRule = [horizontalRule stretchableImageWithLeftCapWidth:0.5 topCapHeight:0];

CGFloat rulerX = CGRectGetMinX(headerRect) + HEADER_LEFT_TEXT_INSET;
CGFloat rulerY = self.printableRect.origin.y + fontSize.height + HEADER_FOOTER_MARGIN_PADDING + PRINT_RULER_MARGIN_PADDING;
CGFloat rulerWidth = headerRect.size.width - HEADER_LEFT_TEXT_INSET - HEADER_RIGHT_TEXT_INSET;
CGFloat rulerHeight = 1;
CGRect ruleRect = CGRectMake(rulerX, rulerY, rulerWidth, rulerHeight);

[horizontalRule drawInRect:ruleRect blendMode:kCGBlendModeNormal alpha:1.0];
于 2011-07-14T07:15:41.343 回答