2015-06-05 52 views
0

我試圖從UIImageView和UITextField添加兩個CALayers到上下文,然後使用UIGraphicsGetImageFromCurrentImageContext()從上下文創建圖像,但是,我似乎無法正確定位文本字段。我希望生成的圖像與最初出現圖像和文本字段的視圖相匹配。相反,文本字段在圖像頂部之外顯示爲一半。目前,我想這樣的事情(這是錯誤的):添加正確定位的圖層到上下文

UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, false, 0.0) 
let ctx = UIGraphicsGetCurrentContext() 
let ht = self.imageView.bounds.size.height 
let wdth = self.imageView.bounds.size.width 
self.imageView.layer.renderInContext(ctx) 

CGContextTranslateCTM(ctx, self.imageView.center.x, self.imageView.center.y) 
CGContextConcatCTM(ctx, self.imageView.transform) 
CGContextTranslateCTM(ctx, -wdth * self.imageView.layer.anchorPoint.x, -ht * self.imageView.layer.anchorPoint.y) 
// Set points for text label here, then... 
self.textLabelTop.layer.renderInContext(ctx) 

let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
return newImage 

我明白CGContextTranslateCTM()CTContextConcatCTM()已經與原來的座標系上應用的背景下,然後將圖層做的,但我不確定如何正確地做到這一點。有人可以提供一個正確技術的例子嗎?

更新:這似乎是一個黑客,但而不是翻譯點的背景下,如果我只是編輯後UIGraphicsGetImageFromCurrentImageContext()之前添加文本字段作爲的UIImageView的子視圖,事情似乎工作,包括與第二個文本框的位置:

self.imageView.addSubview(self.textLabelTop) 
self.imageView.addSubview(self.textLabelBottom) 
UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, false, 0.0) 
let ctx = UIGraphicsGetCurrentContext() 
self.imageView.layer.renderInContext(ctx)   
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
return newImage 

回答

1

你應該知道的convertPoint:toView:可能。試試這個:

UIGraphicsBeginImageContextWithOptions(self.imageView.frame.size, false, 0.0) 
let ctx = UIGraphicsGetCurrentContext() 
self.imageView.layer.renderInContext(ctx) 

let point = self.textLabelTop.superview!.convertPoint(self.textLabelTop.frame.origin, toView: self.imageView) 
CGContextTranslateCTM(ctx, point.x, point.y) 
self.textLabelTop.layer.renderInContext(ctx) 

let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() 
UIGraphicsEndImageContext() 
return newImage 
+0

這實際上工作完美。謝謝! – Ja5onHoffman

+0

我很高興聽到它解決了您的問題! – Bannings

相關問題