我正在尝试将两个CALayers从UIImageView和UITextField添加到上下文,然后使用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
答案 0 :(得分: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