【问题标题】:Swift: UIGraphicsBeginImageContextWithOptions scale factor set to 0 but not appliedSwift:UIGraphicsBeginImageContextWithOptions 比例因子设置为 0 但未应用
【发布时间】:2016-09-24 07:30:59
【问题描述】:

我曾经使用以下代码调整图像大小,并且它在比例因子方面工作得很好。现在使用 Swift 3,我无法弄清楚为什么不考虑比例因子。图像已调整大小,但未应用比例因子。你知道为什么吗?

let layer = self.imageview.layer

UIGraphicsBeginImageContextWithOptions(layer.bounds.size, true, 0)

layer.render(in: UIGraphicsGetCurrentContext()!)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()

print("SCALED IMAGE SIZE IS \(scaledImage!.size)")
print(scaledImage!.scale)

例如,如果我在 iPhone 5 上截屏,图像大小将为 320*568。我以前用完全相同的代码得到 640*1136。什么会导致不应用比例因子?

当我打印图像的比例时,它会根据设备分辨率打印 1、2 或 3,但不会应用于从上下文中获取的图像。

【问题讨论】:

  • @LeoDabus 已尝试但未应用。我也试过 UIScreen.main.scale。
  • @LeoDabus 在提出问题之前我已经检查了您的帖子 :) 问题不是特定于图像的,它可能是任何层。问题是这种从图形上下文中获取图像的方式总是应用适当的比例因子,现在它没有考虑到它。更多的是关于为什么不应用比例因子。

标签: ios swift scale image-resizing uigraphicscontext


【解决方案1】:

scaledImage!.size 不会返回以像素为单位的图像大小。

CGImageGetWidthCGImageGetHeight 返回相同的大小(以像素为单位) 那是image.size * image.scale

如果你想测试一下,首先你必须import CoreGraphics

let imageSize = scaledImage!.size //(320,568)
let imageWidthInPixel = CGImageGetWidth(scaledImage as! CGImage) //640
let imageHeightInPixel = CGImageGetHeight(scaledImage as! CGImage) //1136

【讨论】:

  • 感谢您的相关评论。事实上,这在 Swift 3 中已经改变了,它曾经返回大小像素,所以我很困惑。非常感谢!
  • 为 Swift 4.1 更新:let cgimage = scaledImage?.cgImage print("Image size = \(scaledImage?.size)") print("cgimage width = \(cgimage?.width)") print("cgimage height = \(cgimage?.height)") 示例结果:Image size = Optional((320.0, 320.0)) cgimage width = Optional(640) cgimage height = Optional(640)
猜你喜欢
  • 2021-11-03
  • 2013-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-07-20
  • 1970-01-01
  • 2012-12-10
  • 2011-07-12
  • 1970-01-01
相关资源
最近更新 更多