当前位置: 首页 > 面试题库 >

如何在iOS上调整位图的大小

上官和韵
2023-03-14
问题内容

我想为正在执行的项目调整位图的大小。我设法通过将cgbitmapcontextref转换为像素数组,然后操纵像素数组,然后从操纵的像素数据生成新图像来做到这一点。这种方式非常麻烦。

我想知道是否还有其他方法可以调整CGBitmapContextRef的大小。谢谢。


问题答案:

如果您不愿意CGBitmapContextRef,这里有一些基于UIKit的简单图像大小调整例程。此扩展通过裁剪,缩放,宽高比填充和宽高比拟合(类似于UIImageView提供的一些主要内容模式)来提供调整图像大小的功能。

//
//  UIImage+Resize.swift
//
//  Image resizing extension
//
//  Created by Robert Ryan on 19-May-11.
//  Ported to Swift by Robert Ryan on 12-Feb-15.
//  Modified for Swift 2 by Robert Ryan on 14-Oct-15
//  Modified for Swift 3 by Robert Ryan on 26-May-17
//  Modified for Swift 4 by Robert Ryan on 15-Feb-19
//
//  Inspired by http://ofcodeandmen.poltras.com/2008/10/30/undocumented-uiimage-resizing/
//  but adjusted to support AspectFill and AspectFit modes.
//
//  Copyright (c) 2015 Robert M. Ryan. All rights reserved.
//
//  This work by Robert M. Ryan is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
//  http://creativecommons.org/licenses/by-sa/4.0/

import UIKit

extension UIImage {

    /// Resize the image to be the required size, stretching it as needed.
    ///
    /// - parameter newSize:      The new size of the image.
    /// - parameter contentMode:  The `UIView.ContentMode` to be applied when resizing image.
    ///                           Either `.scaleToFill`, `.scaleAspectFill`, or `.scaleAspectFit`.
    ///
    /// - returns:                Return `UIImage` of resized image.

    func scaled(to newSize: CGSize, contentMode: UIView.ContentMode = .scaleToFill) -> UIImage? {
        switch contentMode {
        case .scaleToFill:
            return filled(to: newSize)

        case .scaleAspectFill, .scaleAspectFit:
            let horizontalRatio = size.width  / newSize.width
            let verticalRatio   = size.height / newSize.height

            let ratio: CGFloat!
            if contentMode == .scaleAspectFill {
                ratio = min(horizontalRatio, verticalRatio)
            } else {
                ratio = max(horizontalRatio, verticalRatio)
            }

            let sizeForAspectScale = CGSize(width: size.width / ratio, height: size.height / ratio)
            let image = filled(to: sizeForAspectScale)
            let doesAspectFitNeedCropping = contentMode == .scaleAspectFit && (newSize.width > sizeForAspectScale.width || newSize.height > sizeForAspectScale.height)
            if contentMode == .scaleAspectFill || doesAspectFitNeedCropping {
                let subRect = CGRect(
                    x: floor((sizeForAspectScale.width - newSize.width) / 2.0),
                    y: floor((sizeForAspectScale.height - newSize.height) / 2.0),
                    width: newSize.width,
                    height: newSize.height)
                return image?.cropped(to: subRect)
            }
            return image

        default:
            return nil
        }
    }

    /// Resize the image to be the required size, stretching it as needed.
    ///
    /// - parameter newSize:   The new size of the image.
    ///
    /// - returns:             Resized `UIImage` of resized image.

    func filled(to newSize: CGSize) -> UIImage? {
        let format = UIGraphicsImageRendererFormat()
        format.opaque = false
        format.scale = scale

        return UIGraphicsImageRenderer(size: newSize, format: format).image { _ in
            draw(in: CGRect(origin: .zero, size: newSize))
        }
    }

    /// Crop the image to be the required size.
    ///
    /// - parameter bounds:    The bounds to which the new image should be cropped.
    ///
    /// - returns:             Cropped `UIImage`.

    func cropped(to bounds: CGRect) -> UIImage? {
        // if bounds is entirely within image, do simple CGImage `cropping` ...

        if CGRect(origin: .zero, size: size).contains(bounds) {
            return cgImage?.cropping(to: bounds * scale).flatMap {
                UIImage(cgImage: $0, scale: scale, orientation: imageOrientation)
            }
        }

        // ... otherwise, manually render whole image, only drawing what we need

        let format = UIGraphicsImageRendererFormat()
        format.opaque = false
        format.scale = scale

        return UIGraphicsImageRenderer(size: bounds.size, format: format).image { _ in
            let origin = CGPoint(x: -bounds.minX, y: -bounds.minY)
            draw(in: CGRect(origin: origin, size: size))
        }
    }

    /// Resize the image to fill the rectange of the specified size, preserving the aspect ratio, trimming if needed.
    ///
    /// - parameter newSize:   The new size of the image.
    ///
    /// - returns:             Return `UIImage` of resized image.

    func scaledAspectFill(to newSize: CGSize) -> UIImage? {
        return scaled(to: newSize, contentMode: .scaleAspectFill)
    }

    /// Resize the image to fit within the required size, preserving the aspect ratio, with no trimming taking place.
    ///
    /// - parameter newSize:   The new size of the image.
    ///
    /// - returns:             Return `UIImage` of resized image.

    func scaledAspectFit(to newSize: CGSize) -> UIImage? {
        return scaled(to: newSize, contentMode: .scaleAspectFit)
    }

}

extension CGSize {
    static func * (lhs: CGSize, rhs: CGFloat) -> CGSize {
        return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
    }
}

extension CGPoint {
    static func * (lhs: CGPoint, rhs: CGFloat) -> CGPoint {
        return CGPoint(x: lhs.x * rhs, y: lhs.y * rhs)
    }
}

extension CGRect {
    static func * (lhs: CGRect, rhs: CGFloat) -> CGRect {
        return CGRect(origin: lhs.origin * rhs, size: lhs.size * rhs)
    }
}

对于Swift 2复制,请参阅此答案的先前版本。



 类似资料:
  • 问题内容: 下面的代码调整位图的大小并保持宽高比。我想知道是否有一种更有效的大小调整方法,因为我想到了我正在编写android API中已经可用的代码。 问题答案: 使用方法:)

  • 我有下面的代码,它设置了一个特定大小的窗口。它还从外部URL加载图像。

  • 问题内容: 您好,我有一个QR码图像,我想调整它的大小,当我尝试使用此代码将其调整为小图像时,我总是得到模糊的图像,并且扫描时QR码不再有效,但是当我使用相同的代码将大小调整为大尺寸图像时,它可以正常工作: 有什么问题,我不清楚,请至少给我一个提示,谢谢。 问题答案: 我使用仿射变换来完成此任务,这是我的代码,希望对您有所帮助

  • 本文向大家介绍如何在PHP中调整图片大小?,包括了如何在PHP中调整图片大小?的使用技巧和注意事项,需要的朋友参考一下 可以使用ImageMagick或GD功能调整图像大小。如果使用了GD的功能,则在对原始数码相机的图像进行采样时,图像文件的大小也会减小。我们将在下面的代码中看到如何使用GD调整图像大小。

  • 问题内容: 我正在使用 Swift 和Parse.com开发适用于iOS的应用程序 我试图让用户从图像选择器中选择一张图片,然后将所选图像的大小调整为200x200像素,然后再上传到我的后端。 Parse.com有一个用于Instagram复制应用程序的教程,名为“ AnyPic”,其中提供了用于调整图像大小的代码,但这是在Objective- C中。 如何在Swift中为所选图片创建200x20

  • Photoshop 中的“图像大小”命令包含一种可以保留细节,并在放大图像时提供更优锐度的方法。未裁剪的原始图像(左图);调整大小后的锐化图像(右图) 此外,还更新了 Photoshop 的图像大小对话框以方便使用: 通过一个窗口显示调整参数的预览图像。 调整对话框的大小也将调整预览窗口的大小。 可从对话框右上角的齿轮菜单内启用和禁用“缩放样式”选项。 从“尺寸”弹出菜单中,选取其他度量单位显示最