簡體   English   中英

在Cocoa AppKit中平滑地拉伸PNG

[英]Stretch PNGs smoothly in Cocoa AppKit

在類似這樣的問題, 一個是展示了如何使用UIKit中的

-(UIImage *)stretchableImageWithLeftCapWidth:(NSInteger)leftCapWidth topCapHeight:(NSInteger)topCapHeight

輕松拉伸PNG,例如在像氣泡這樣的iChat中插入文本時。 我想在使用CoreGraphics或一些NSImage相關API的常規AppKit / Cocoa /桌面應用程序上執行相同操作但無法找到等效方法。 有人知道如何在AppKit中執行此操作嗎?

這是一個我掀起的功能,需要1個圖像,並且只是中間的...

在此輸入圖像描述

-(NSImage *)image:(NSImage *)image leftCapWidth:(float)leftWidth middleWidth:(float)middleWidth rightCapWidth:(float)rightWidth {

    // Calculate the new images dimensions
    float imageWidth = leftWidth + middleWidth + rightWidth;
    float imageHeight = image.size.height;

    // Generate the left image
    NSRect rectLeft = NSMakeRect(0, 0, leftWidth, imageHeight);
    NSImage *imageLeft = [[NSImage alloc] initWithSize:rectLeft.size];
    if (imageLeft.size.width > 0) {
        [imageLeft lockFocus];
        [image drawInRect:rectLeft fromRect:rectLeft operation:NSCompositeCopy fraction:1.0];
        [imageLeft unlockFocus];
    }

    // Generate the middle image
    NSRect rectMiddle = NSMakeRect(0, 0, image.size.width - (rightWidth + leftWidth), imageHeight);
    NSImage *imageMiddle = [[NSImage alloc] initWithSize:rectMiddle.size];
    if (imageMiddle.size.width > 0) {
        [imageMiddle lockFocus];
        [image drawInRect:rectMiddle fromRect:NSMakeRect(leftWidth, 0, rectMiddle.size.width, imageHeight) operation:NSCompositeCopy fraction:1.0];
        [imageMiddle unlockFocus];
    }

    // Generate the right image
    NSRect rectRight = NSMakeRect(0, 0, rightWidth, imageHeight);
    NSImage *imageRight = [[NSImage alloc] initWithSize:rectRight.size];
    if (imageRight.size.width > 0) {
        [imageRight lockFocus];
        [image drawInRect:rectRight fromRect:NSMakeRect(image.size.width - rightWidth, 0, rightWidth, imageHeight) operation:NSCompositeCopy fraction:1.0];
        [imageRight unlockFocus];
    }

    // Combine the images
    NSImage *newImage = [[[NSImage alloc] initWithSize:NSMakeSize(imageWidth,  imageHeight)] autorelease];
    if (newImage.size.width > 0) {
        [newImage lockFocus];
        NSDrawThreePartImage(NSMakeRect(0, 0, imageWidth, imageHeight), imageLeft, imageMiddle, imageRight, NO, NSCompositeSourceOver, 1, NO); 
        [newImage unlockFocus];
    }

    // Release the images and return the new image
    [imageLeft release];
    [imageMiddle release];
    [imageRight release];

    return newImage;
}

只需使用 - [NSImage drawInRect:fromRect:operation:fraction:],並將NSZeroRect作為fromRect傳遞; 參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM