我该如何绘制图像?

时间:2011-11-22 05:25:33

标签: iphone objective-c uiimage draw

我在objective-c上编程。我的图像有一条线(见下图)(1 x 30)像素。

enter image description here

如何从这一行获得UIImage(50 x 30)(见下文)?

enter image description here

4 个答案:

答案 0 :(得分:0)

创建一个大小为50 * 30的CGBitmapContext,而不是只使用CGContextDrawImage在上下文中绘制该图像。

之后使用CGBitmapContextCreateImage[UIImage imageWithCGImage:]创建UIImage

CGContextRef CreateBitmapContext(int pixelsWide, int pixelsHigh)
{
    CGContextRef    context = NULL;
    CGColorSpaceRef colorSpace;
    int             bitmapByteCount;
    int             bitmapBytesPerRow;

    bitmapBytesPerRow   = (pixelsWide * 4); // RGBA
    bitmapByteCount     = (bitmapBytesPerRow * pixelsHigh);

    colorSpace = CGColorSpaceCreateDeviceRGB();
    context = CGBitmapContextCreate (NULL,
                                     pixelsWide,
                                     pixelsHigh,
                                     8,      // bits per component
                                     bitmapBytesPerRow,
                                     colorSpace,
                                     kCGImageAlphaPremultipliedLast);
    NSCAssert(context != NULL, @"cannot create bitmap context");
    CGColorSpaceRelease( colorSpace );

    return context;
}

CGContextRef context = CreateBitmapContext(50, 30);
UIImage *yourLineImage = ...;
CGImageRef cgImg = [yourLineImage CGImage];
for (int i = 0; i < 50; i++) {
    CGRect rect;
    rect.origin.x = i;
    rect.origin.y = 0;
    rect.size.width = 1;
    rect.size.height = 30;
    CGContextDrawImage(context, rect, cgImg);
}
CGImageRef output = CGBitmapContextCreateImage(context);
UIImage *result = [UIImage imageWithCGImage:output];

答案 1 :(得分:0)

如果您只想绘制图片,可能需要尝试UIImagedrawInRect:方法。

您通常希望从自定义UIView的drawRect:中调用此内容。

在Cocoa(和Cocoa-Touch)中有不同的绘制方法,所以这里是Apple的Drawing and Printing Guide for iOS

答案 2 :(得分:0)

如果您的线条颜色简单,请尝试这种懒惰的方法:

UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 50, 30)];
[line setImage:[UIImage imageNamed:@"your gray line"]];
[self.view addSubView:line];

答案 3 :(得分:0)

您可以在iOS中使用+[UIColor colorWithPatternImage]

NSString *path = 
    [[NSBundle mainBundle] pathForResource:@"<# the pattern file #>" ofType:@"png"];
UIColor *patternColor = [UIColor colorWithPatternImage:
    [UIImage imageWithContentsOfFile:path]];
/* use patternColor anywhere as a regular UIColor instance */

无缝模式更好用。对于OSX,您可以使用+[NSColor colorWithPatternImage]方法。