在iOS上使用核心图形在PDF中嵌入超链接
我正在尝试做一件非常简单的事情:在一个PDF文件中写一个URL,用户可以实际点击它 我确信使用它是可以做到的。我正在寻找的是使用核心图形做同样的事情,因为我已经在我的应用程序中的所有代码都已经使用了这些方法 ==编辑== 我想我找到了一些东西:在iOS上使用核心图形在PDF中嵌入超链接,ios,pdf,hyperlink,core-graphics,Ios,Pdf,Hyperlink,Core Graphics,我正在尝试做一件非常简单的事情:在一个PDF文件中写一个URL,用户可以实际点击它 我确信使用它是可以做到的。我正在寻找的是使用核心图形做同样的事情,因为我已经在我的应用程序中的所有代码都已经使用了这些方法 ==编辑== 我想我找到了一些东西:uigraphicssetpdfcontexturerforrect,但我无法让它工作 我使用的是类似于: NSURL *url = [NSURL URLWithString:@"http://www.google.com"]; UIGraphicsSet
uigraphicssetpdfcontexturerforrect
,但我无法让它工作
我使用的是类似于:
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
UIGraphicsSetPDFContextURLForRect( url, CGRectMake(0, 0, 100, 100));
但是,不能单击rect。好的,我设法找出了它不起作用的原因 核心图形上下文是“反向的”,即原点位于页面的左下角,而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);
}
这种方法的作用是:
- 获取当前上下文并将转换应用于提供的rect,以便在
将框标记为可单击时,获取在标记框时可用的rectUIGraphicsSetPDFContexturerForRect
- 使用上述方法将新的rect(
)标记为可单击xformRect
- 保存当前上下文,以便以后执行的任何操作(颜色、大小、属性等)都不会在当前上下文中保持持久性
- 在提供的矩形中绘制文本(现在使用UIKit坐标系)
- 要恢复上下文状态,请执行以下操作:
- 这里是Swift 5的转换代码
let context = UIGraphicsGetCurrentContext()
let ctm = context?.ctm
// Translate the origin to the bottom left.
// Notice that 842 is the size of the PDF page.
ctm?.translatedBy(x: 0.0, y: 842)
// Flip the handedness of the coordinate system back to right handed.
ctm?.scaledBy(x: 1.0, y: -1.0)
var xformRect: CGRect? = nil
if let ctm = ctm {
xformRect = frameRect.applying(ctm)
}
let url = URL(string: text)
if let url = url {
UIGraphicsSetPDFContextURLForRect(url, xformRect ?? CGRect.zero)
}
context?.saveGState()
let attributesDict =[
.foregroundColor: UIColor.blue,
.underlineStyle: NSUnderlineStyle.single.rawValue
]
let attString = NSMutableAttributedString(string: url?.absoluteString ?? "", attributes: attributesDict as? [NSAttributedString.Key : Any])
attString?.draw(in: frameRect)
context?.restoreGState()