没有质量松散的图像比例
Posted
技术标签:
【中文标题】没有质量松散的图像比例【英文标题】:Image scale without loose quality 【发布时间】:2015-12-22 10:50:11 【问题描述】:我尝试从 API 缩放图像,但是当我尝试在我的 tableview 中调整它时遇到了问题。 我想用正确的屏幕宽度缩放图像以进行显示并保持比例图像。对于我的表格视图中的每个单元格,我都有这个:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = portfolioTableView.dequeueReusableCellWithIdentifier("OnePhotoCell", forIndexPath: indexPath) as! OnePhotoCell
cell.onePhotoImageView.image = arrayPhotos[indexPath.row].imagePhoto
单元格包含带有内容模式方面填充的 imageView。为了保持比例,我也这样做:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
let image = self.arrayPhotos[indexPath.row].imagePhoto
return image.size.height
为了缩放我的图像,我使用了这个函数:
func resizeImage(image: UIImage) -> UIImage
let oldWidth = Float(image.size.width)
let scaleFactor = Float(self.view.frame.width) / oldWidth
let newHeight = Float(image.size.height) * scaleFactor
let newWidth = oldWidth * scaleFactor
let size = CGSize(width: CGFloat(newWidth), height: CGFloat(newHeight))
let newRect = CGRectIntegral(CGRectMake(0,0, CGFloat(newWidth), CGFloat(newHeight)))
let imageRef = image.CGImage
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(context, .High)
let flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, CGFloat(newHeight))
CGContextConcatCTM(context, flipVertical)
CGContextDrawImage(context, newRect, imageRef)
let newImageRef = CGBitmapContextCreateImage(context)! as CGImage
let newImage = UIImage(CGImage: newImageRef)
UIGraphicsEndImageContext()
return newImage
这个功能的问题是比例保持不变,但我的图像质量下降。 有人知道如何解决这个问题吗?
【问题讨论】:
【参考方案1】:试试:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
let image = self.arrayPhotos[indexPath.row].imagePhoto
return image.size.height / UIScreen.mainScreen().scale
【讨论】:
感谢您的回复,我试试这个,但它没有任何改变【参考方案2】:试试 scaleFactor 应该是
let scaleFactor = Float(self.view.frame.width * UIScreen.mainScreen().nativeScale) / oldWidth
和
UIGraphicsBeginImageContextWithOptions(size, false, 1.0)
【讨论】:
以上是关于没有质量松散的图像比例的主要内容,如果未能解决你的问题,请参考以下文章