You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift macOS应用如何给图片调整尺寸、添加内边距、背景及阴影

macOS Swift 原生图片处理实现方案

实现逻辑

完全基于AppKit原生API实现,无需引入第三方库,可直接覆盖调整尺寸、加内边距、设置背景色、添加阴影四个需求:

  1. 读取本地路径的原始图片
  2. 按目标尺寸等比例缩放原图,避免拉伸变形
  3. 计算叠加内边距后的画布总尺寸
  4. 填充画布背景色
  5. 配置阴影属性后将缩放后的原图绘制到画布中心
  6. 导出处理后的图片到指定路径

完整实现代码

import AppKit

func processImage(inputURL: URL, targetSize: NSSize, padding: CGFloat, bgColor: NSColor, shadow: NSShadow?, outputURL: URL) throws {
    // 1. 读取原始图片
    guard let inputImage = NSImage(contentsOf: inputURL) else {
        throw NSError(domain: "ImageProcessError", code: -1, userInfo: [NSLocalizedDescriptionKey: "无法读取输入图片"])
    }
    
    // 2. 等比例计算原图缩放后的实际尺寸(避免拉伸)
    let originalSize = inputImage.size
    let widthRatio = targetSize.width / originalSize.width
    let heightRatio = targetSize.height / originalSize.height
    let scaleRatio = min(widthRatio, heightRatio)
    let scaledSize = NSSize(width: originalSize.width * scaleRatio, height: originalSize.height * scaleRatio)
    
    // 3. 计算画布总尺寸(加上左右上下内边距)
    let canvasSize = NSSize(width: scaledSize.width + padding * 2, height: scaledSize.height + padding * 2)
    
    // 4. 初始化画布开始绘制
    let processedImage = NSImage(size: canvasSize)
    processedImage.lockFocus()
    defer { processedImage.unlockFocus() }
    
    // 5. 填充背景色
    bgColor.setFill()
    NSRect(origin: .zero, size: canvasSize).fill()
    
    // 6. 设置阴影(如果有传阴影参数)
    shadow?.set()
    
    // 7. 将缩放后的原图绘制到画布中心
    let drawOrigin = NSPoint(x: padding + (targetSize.width - scaledSize.width)/2, y: padding + (targetSize.height - scaledSize.height)/2)
    inputImage.draw(in: NSRect(origin: drawOrigin, size: scaledSize))
    
    // 8. 导出为PNG格式
    guard let tiffData = processedImage.tiffRepresentation,
          let bitmapRep = NSBitmapImageRep(data: tiffData),
          let pngData = bitmapRep.representation(using: .png, properties: [:]) else {
        throw NSError(domain: "ImageProcessError", code: -2, userInfo: [NSLocalizedDescriptionKey: "图片导出失败"])
    }
    
    // 9. 写入到输出路径
    try pngData.write(to: outputURL)
}

参数调整说明

  • 调整尺寸:修改传入的targetSize参数即可,代码默认保持原图比例缩放,不需要等比例可以直接删除比例计算逻辑,强制用传入的targetSize作为缩放后尺寸
  • 添加内边距:修改padding参数即可,单位为像素,四个方向内边距统一设置,需要单独设置不同方向内边距可以把参数拆分为上、下、左、右四个单独变量
  • 设置背景色:传入对应的NSColor实例即可,需要透明背景可以传NSColor.clear
  • 添加阴影:自定义NSShadow实例配置属性,常见柔和阴影配置参考:
    let customShadow = NSShadow()
    customShadow.shadowColor = NSColor.black.withAlphaComponent(0.3)
    customShadow.shadowOffset = NSSize(width: 0, height: -3)
    customShadow.shadowBlurRadius = 6
    

调用示例

do {
    let inputURL = URL(fileURLWithPath: "../myFiles/myFile.png")
    let outputURL = URL(fileURLWithPath: "../myFiles/processedResult.png")
    let shadow = NSShadow()
    shadow.shadowColor = NSColor.black.withAlphaComponent(0.3)
    shadow.shadowOffset = NSSize(width: 0, height: -3)
    shadow.shadowBlurRadius = 6
    try processImage(inputURL: inputURL, targetSize: NSSize(width: 200, height: 200), padding: 20, bgColor: .white, shadow: shadow, outputURL: outputURL)
    print("图片处理完成")
} catch {
    print("处理出错:\(error.localizedDescription)")
}

内容的提问来源于stack exchange,提问作者Oscar Franco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:36:00