Jap
Jap

Reputation: 11

How can I convert the following code about Core Graphics into Swift?

- (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);
}

It's code I found to make url's in a pdf clickable.

I'm still getting the hang of objective-c so your help is greatly apprecaited. Thank you very much in advance!

Right now here is what I have translated, and I'm pretty sure there are a couple mistakes:

    func drawTextLink(text: NSString, frameRect: CGRect) {
let context: CGContext = UIGraphicsGetCurrentContext()!
    var c = context.ctm

    let cc = CGAffineTransform.translatedBy(c)
    cc.(0.0, 842)

}

Upvotes: 0

Views: 233

Answers (1)

Syed Qamar Abbas
Syed Qamar Abbas

Reputation: 3677

Above method in Swift 4.0 should be like this.

func drawTextLink(text: String, frame: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else {return}
    let ctm = context.ctm
    ctm.translatedBy(x: 0.0, y: 842)
    ctm.scaledBy(x: 1.0, y: -1.0)
    let newFrame = frame.applying(ctm)
    guard let url = URL(string: text) else {return}
    UIGraphicsSetPDFContextURLForRect(url, newFrame)
    context.saveGState()
    let dict = [NSAttributedStringKey.underlineStyle: 1, .foregroundColor: UIColor.red] as [NSAttributedStringKey : Any]
    let attrString = NSAttributedString(string: text, attributes: dict)
    attrString.draw(in: frame)
    context.restoreGState()
}

Upvotes: 1

Related Questions