swift - 在 Swift-OSX 中的 NSImage 上写入文本

标签 swift macos nsimage

我有以下 objective-c 代码将文本写入图像。我是 swift 的新手。我怎样才能在 Swift 中做到这一点?

float width = 10.0;
float height = 10.0;

NSImage *finalImage = [[NSImage alloc] initWithSize:NSMakeSize(width, height)];

//  obtain images - your sources may vary
NSImage *overlay = [[NSImage alloc] initWithData:[NSData dataWithContentsOfFile:@"/path/to/overlay_image.jpg"]];
NSImage *mainImage = [[NSImage alloc] initWithData:[NSData dataWithContentsOfFile:@"/path/to/main_image.jpg"]];

[finalImage lockFocus];

// draw the base image
[mainImage drawInRect:NSMakeRect(0, 0, width, height) 
                      fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

// draw the overlay image at some offset point
[overlay drawInRect:NSMakeRect(10, 10, [overlay size].width, [overlay size].height) 
             fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

[finalImage unlockFocus];

NSData *finalData = [finalImage TIFFRepresentation];

[[[NSBitmapImageRep imageRepWithData:finalData] representationUsingType:NSJPEGFileType properties:nil] writeToFile:[NSString stringWithFormat:@"/path/to/folder/new_image.jpg"] atomically:YES];

更新:

我有以下方法将字符串绘制到图像上。但是当我使用此方法时,我会裁剪掉图像部分。似乎有问题。请提出建议。

func drawText(image :NSImage) ->NSImage
{
    let text = "Sample Text"
    let font = NSFont.boldSystemFont(ofSize: 18)
    let imageRect = CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)

    let textRect = CGRect(x: 5, y: 5, width: image.size.width - 5, height: image.size.height - 5)
    let textStyle = NSMutableParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
    let textFontAttributes = [
        NSFontAttributeName: font,
        NSForegroundColorAttributeName: NSColor.white,
        NSParagraphStyleAttributeName: textStyle
    ]

    let im:NSImage = NSImage(size: image.size)

    let rep:NSBitmapImageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(image.size.width), pixelsHigh: Int(image.size.height), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSCalibratedRGBColorSpace, bytesPerRow: 0, bitsPerPixel: 0)!

    im.addRepresentation(rep)

    im.lockFocus()

    image.draw(in: imageRect)
    text.draw(in: textRect, withAttributes: textFontAttributes)

    im.unlockFocus()

    return im
}

最佳答案

这是 Swift 3 中的代码

let width: CGFloat = 10.0
let height: CGFloat = 10.0

let finalImage = NSImage(size: NSMakeSize(width, height))

//  obtain images - your sources may vary
var overlay: NSImage?
var mainImage: NSImage?

if let url = URL(string: "/path/to/overlay_image.jpg") {
    do {
        let data = try Data(contentsOf: url)
        overlay = NSImage(data: data)
    } catch {
        print("Unable to get data")
    }
}

if let url = URL(string: "/path/to/main_image.jpg") {
    do {
        let data = try Data(contentsOf: url)
        mainImage = NSImage(data: data)
    } catch {
        print("Unable to get data")
    }
}

finalImage.lockFocus()

// draw the base image
mainImage?.draw(in: NSMakeRect(0, 0, width, height), from: NSZeroRect, operation: NSCompositingOperation.sourceOver, fraction: 1.0)

// draw the overlay image at some offset point
if overlay != nil {
    overlay?.draw(in: NSMakeRect(10, 10, overlay!.size.width, overlay!.size.height), from: NSZeroRect, operation: NSCompositingOperation.sourceOver, fraction: 1.0)
}

finalImage.unlockFocus()

if let finalData = finalImage.tiffRepresentation, let url = URL(string: "/path/to/folder/new_image.jpg") {
    do {
        try NSBitmapImageRep(data: finalData)?.representation(using: NSJPEGFileType, properties: [:])?.write(to: url)
    } catch {
        print("Failed to write")
    }
}

关于swift - 在 Swift-OSX 中的 NSImage 上写入文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46764667/

相关文章:

swift - 如何修复 Swift Sort 函数错误?

arrays - 如何 swift 将调用委托(delegate)给 [0..<n]?

swift - 如何使用类型约束调用协议(protocol)扩展默认实现

macos - 如何对 Go 工作区进行碎片化

iphone - 如何使用 Core Data 和 RestKit 映射和存储图像?

objective-c - 如何在 Objective-c/Cocoa (OSX) 中做出完美的裁剪(不改变质量)

c# - 从路径中获取图像缩略图

ios - 错误访问物理场导致应用程序 SWIFT、XCODE 崩溃

macos - 如何使用 swift 在窗口中拖动 ImageView (OS X 不是 IOS)

ios - Xcode - 如何修复 'NSUnknownKeyException',原因 : … this class is not key value coding-compliant for the key X"error?