【问题标题】:Add correctly positioned layers to context将正确定位的图层添加到上下文
【发布时间】:2015-06-05 02:05:40
【问题描述】:

我正在尝试将 UIImageView 和 UITextField 中的两个 CALayer 添加到上下文,然后使用 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() 必须将原始坐标系应用于上下文,然后放置图层,但我不确定如何正确执行此操作。有人可以提供适当技术的示例吗?

更新:这似乎是一个 hack,但不是将点转换为上下文,如果我只是在编辑之后和 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

【问题讨论】:

    标签: ios iphone swift ios8


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 2022-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多