使UIImage适合UIView内的UIImageView

DrW*_*hat 7 uitableview uiimageview swift

在使用UIImageView中的正确宽高比时,我在设置图像时遇到了很多麻烦.

最初从plist插入核心数据的所有图像都符合正确的宽高比,但是当使用应用程序(来自现有图像库)添加图像时,三个视图中的两个视图中的图像看起来比视图本身大 - 所以只显示照片的左上角.在下面的屏幕截图中,表格的顶行显示通过plist添加的图像,接下来的两行(MY RECORDS)显示不限于视图的照片.

在此输入图像描述

上述视图中的单元格以通常的方式创建,然后在其自己的方法中进行配置,其中定义了属性.

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
    self.configureCell(cell, indexPath: indexPath)
    return cell
}

    func configureCell(cell: UITableViewCell, indexPath: NSIndexPath)
{
    let record = fetchedResultsController.objectAtIndexPath(indexPath) as! Record
    cell.textLabel!.text = record.subject
    cell.detailTextLabel!.text = record.shortDetails

    if let imageArray = imagesForRecord(record)
    {
        if imageArray.count > 0
        {
            cell.imageView?.contentMode = .ScaleAspectFit
            cell.imageView?.clipsToBounds = true
            cell.imageView?.image = imageArray[Int(record.featureImageIndex)]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是图像不会缩放,也不会在imageView的范围内剪切.最初加载的图像(如熊)不需要设置contentMode或clipsToBounds.

我在不同的视图控制器(称为VC2)中有相同的问题,但此视图是使用故事板定义的.我有一个UIImage视图,它被约束到具有固定大小约束的UIView的所有方面.UIImage视图设置为Aspect Fit,但是当我从设备库中设置图像时,它看起来像上面的图片 - 宽高比是正确的,但只显示图像的上角.

在此输入图像描述

在此输入图像描述

在另一个视图中,我有与VC2几乎相同的故事板布局,但在这里它按预期工作.我看不出约束,属性和使用相同照片(来自库)的任何差异.

在此输入图像描述

在此输入图像描述

我看不出任何差异,我无法想象如何从这里调试.毫无疑问,我误解了关于Aspect Fit或如何应用它的一些非常简单的事情.

Der*_*123 0

也许添加这样的东西:

class func imageWithImage(image: UIImage, scaledToSize newSize: CGSize) -> UIImage {
    //UIGraphicsBeginImageContext(newSize);
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
    image.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
    var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}
Run Code Online (Sandbox Code Playgroud)