2012-10-12 102 views
2

我目前通过使用CALayerrenderInContext方法从iOS中的UIView创建PDF文档。iOS从UIViews创建PDF

我面临的问题是标签的锐度。我创建了一个UILabel子类覆盖drawLayer像这样:

/** Overriding this CALayer delegate method is the magic that allows us to draw a vector version of the label into the layer instead of the default unscalable ugly bitmap */ 
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx { 
    BOOL isPDF = !CGRectIsEmpty(UIGraphicsGetPDFContextBounds()); 
    if (!layer.shouldRasterize && isPDF) 
     [self drawRect:self.bounds]; // draw unrasterized 
    else 
     [super drawLayer:layer inContext:ctx]; 
} 

这种方法让我画好的清晰的文字,然而,问题是,我不拥有控制权的其他意见。有没有什么方法可以让我为嵌入UITableViewUIButton的标签做类似的事情。我想我正在寻找一种方法来遍历视图堆栈,并做一些让我绘制更清晰的文本。

下面是一个例子: 本文呈现很好(我的自定义的UILabel子类) Imgur

在标准文本分段控制不是尖锐:

Imgur

编辑:我得到的上下文画成我的PDF如下:

UIGraphicsBeginPDFContextToData(self.pdfData, CGRectZero, nil); 
pdfContext = UIGraphicsGetCurrentContext(); 
UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0, 612, 792), nil); 
[view.layer renderInContext:pdfContext]; 
+0

你是如何获得你的语境”用'renderInContext'重新绘制?我想知道你是否可以在那里翻倍。 – matt

+0

更新了我的文章。 – danielbeard

回答

2

我最终遍历了视图层次结构,并将每个UILabel设置为覆盖drawLayer的我的自定义子类。

这里是我穿过的看法:

我该如何改变类:

+(void) setClassForLabel: (UIView*) label { 
    static Class myFancyObjectClass; 
    myFancyObjectClass = objc_getClass("UIPDFLabel"); 
    object_setClass(label, myFancyObjectClass); 
} 

比较:

老:

Image

新:

Imgur

不知道是否有更好的方式来做到这一点,但它似乎为我的目的工作。

编辑:找到一个更通用的方法来做到这一点,不涉及改变类或遍历整个视图层次结构。我正在使用方法swizzling。如果需要,此方法还可让您执行诸如围绕具有边框的每个视图等酷炫事物。首先,我创建了一个类别UIView+PDF与我的drawLayer方法的定制实现,那么在load方法我用的是以下几点:

// The "+ load" method is called once, very early in the application life-cycle. 
// It's called even before the "main" function is called. Beware: there's no 
// autorelease pool at this point, so avoid Objective-C calls. 
Method original, swizzle; 

// Get the "- (void) drawLayer:inContext:" method. 
original = class_getInstanceMethod(self, @selector(drawLayer:inContext:)); 
// Get the "- (void)swizzled_drawLayer:inContext:" method. 
swizzle = class_getInstanceMethod(self, @selector(swizzled_drawLayer:inContext:)); 
// Swap their implementations. 
method_exchangeImplementations(original, swizzle); 

从这里的代码工作:http://darkdust.net/writings/objective-c/method-swizzling

+0

WTF @ setClassForLabel -_-,发挥良好。 – 0xSina

+0

我怎样才能使这个两次?辉煌。 – matt

+1

你愿意分享一下'drawLayer'的自定义实现吗? –