【问题标题】:CGImage DisplayCG图像显示
【发布时间】:2015-02-09 08:01:16
【问题描述】:

我有一个功能,当用户触摸屏幕时,我想在图像上下文中显示图像。代码编译正确,但没有图像出现。我确信错误在于这个函数,因为我不确定我是否完全理解如何显示图像。我要以正确的方式生成图像吗?

func generateImage() -> UIImage {

    let centerX = CGRectGetWidth(self.frame) / 2
    let centerY = CGRectGetHeight(self.frame) / 2
    var startPoint = CGPoint(x: centerX, y: centerY)
    var endPoint = CGPoint(x: centerX, y: centerY)
    let imageRect = CGRect(x: centerX, y: centerY, width: 150, height: 150)
    let insideImage = UIImage(named: "at")
    let insideCGImage = insideImage?.CGImage

    // Generate the image
    // Begin an image context
    UIGraphicsBeginImageContext(self.frame.size)
    let imageContext = UIGraphicsGetCurrentContext()
    // Use CG to draw the image into the image context
    CGContextDrawImage(imageContext, imageRect, insideCGImage)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return image
}

【问题讨论】:

  • 您是否将图像添加到视图中?
  • 在视图控制器中,我有一个 UIView 引用该类,称为 ImageDrag。
  • @IBOutlet weak var mainImage: ImageDrag!

标签: swift uiimage cgimage


【解决方案1】:

你必须使用你的函数的返回值:

mainImage = generateImage()

否则,该值不会在任何地方使用并保持未使用状态。

如果您的方法在其他类中,您必须创建一个实例并调用该方法:

var classInstance = YourClassWithTheFunction()

然后你可以这样调用方法:

mainImage = classInstance.generateImage()

【讨论】:

  • 我不确定我是否跟随。我的控制器中的出口变量 mainImage 无法访问另一个类 ImageDrag 中的 generateImage 函数。当我尝试它时,我得到了很多错误。
  • 你必须创建一个实例并调用方法: var classInstance = YourClassWithTheFunction() 然后你可以这样调用方法: classInstance.generateImage()
  • 我得到的错误出现在这段代码的第三行:@IBOutlet weak var mainImage: ImageDrag! var classInstance = ImageDrag(frame: CGRect()) var mainImage = classInstance.ImageDrag() XCode 出现一个错误,指出“ViewController.Type”没有名为“classInstance”的成员
  • 我应该补充一点,我在 ImageDrag 类中也有一个 this:override init(frame: CGRect) { super.init(frame: frame) self.layer.contents = self.generateImage().CGImage }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-30
  • 2015-10-30
相关资源
最近更新 更多