gpt4 book ai didi

ios - 在 iOS 上使用 Core Graphics 在 PDF 中嵌入超链接

转载 作者:可可西里 更新时间:2023-11-01 05:03:59 24 4
gpt4 key购买 nike

我正在尝试做一件非常简单的事情:在 PDF 文件中写入一个用户可以实际点击的 URL。

我确定使用 libharu可以办到。我正在寻找的是使用 Core Graphics 做同样的事情,因为我的应用程序中已有的整个代码已经在使用这些方法。

== 编辑 ==

我想我找到了一些东西:UIGraphicsSetPDFContextURLForRect 但我无法让它工作。

我正在使用类似的东西:

NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
UIGraphicsSetPDFContextURLForRect( url, CGRectMake(0, 0, 100, 100));

不过,该矩形不可点击。

最佳答案

好吧,我设法弄清楚了为什么它不起作用。

Core Graphics 上下文在原点位于页面左下角的意义上是“颠倒的”,而 UIKit 的原点位于左上角。

这是我想出的方法:

- (void) drawTextLink:(NSString *) text inFrame:(CGRect) frameRect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGAffineTransform ctm = CGContextGetCTM(context);

// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
CGAffineTransformTranslate(ctm, 0.0, 842);

// Flip the handedness of the coordinate system back to right handed.
CGAffineTransformScale(ctm, 1.0, -1.0);

// Convert the update rectangle to the new coordiante system.
CGRect xformRect = CGRectApplyAffineTransform(frameRect, ctm);

NSURL *url = [NSURL URLWithString:text];
UIGraphicsSetPDFContextURLForRect( url, xformRect );

CGContextSaveGState(context);
NSDictionary *attributesDict;
NSMutableAttributedString *attString;

NSNumber *underline = [NSNumber numberWithInt:NSUnderlineStyleSingle];
attributesDict = @{NSUnderlineStyleAttributeName : underline, NSForegroundColorAttributeName : [UIColor blueColor]};
attString = [[NSMutableAttributedString alloc] initWithString:url.absoluteString attributes:attributesDict];

[attString drawInRect:frameRect];

CGContextRestoreGState(context);
}

这个方法的作用是:

  • 获取当前上下文并对提供的矩形应用转换,以便在 UIGraphicsSetPDFContextURLForRect 将其标记为可点击时获得在标记框时有效的矩形
  • 使用上述方法将新矩形 (xformRect) 标记为可点击
  • 保存当前上下文,以便以后所做的任何事情(颜色、大小、属性等)都不会在当前上下文中保持不变
  • 在提供的矩形中绘制文本(现在使用 UIKit 坐标系)
  • 恢复上下文GState

关于ios - 在 iOS 上使用 Core Graphics 在 PDF 中嵌入超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14748204/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com