在Swift-OSX中的NSImage上写文本

时间:2017-10-16 07:06:11

标签: swift macos nsimage

我有以下目标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];

更新

我有以下方法将一个字符串绘制到一个Image ..但是当我使用这个方法时,我被裁剪掉了图像部分。看到它出了问题......请指教。

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
}

1 个答案:

答案 0 :(得分:1)

此处的代码位于 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")
    }
}