2013-12-04 5 views
3

Я использую приведенный ниже код, чтобы нарисовать UIImage. Я использую некоторые вершины рисовать, в этом случае площадь:Рисование UIImage с использованием CGBitmapContextCreate - Изображение полного размера для текстуры - iOS

- (UIImage *)drawTexture : (NSArray *)verticesPassed { 

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); 

    CGContextRef con = CGBitmapContextCreate(NULL, 
                   1000, 
                   1000, 
                   8, 
                   0, 
                   rgbColorSpace, 
                   kCGImageAlphaPremultipliedFirst); 

    CGColorSpaceRelease(rgbColorSpace); 

    CGContextSetLineWidth(con, 10); 

    Line * start = [verticesPassed objectAtIndex:0]; 
    StandPoint * startPoint = start.origin; 

    CGContextMoveToPoint(con, [startPoint.x floatValue], [startPoint.y floatValue]); 

    for (Line * vertice in verticesPassed) { 
     StandPoint * origin = vertice.origin; 
     CGContextAddLineToPoint(con, [origin.x floatValue], [origin.y floatValue]); 
     NSLog(@"Texutre point is %f %f", [origin.x floatValue], [origin.y floatValue]); 
    } 

    CGContextSetFillColorWithColor(con, [UIColor greenColor].CGColor); 

    CGContextFillPath(con); 

    [self drawText:con startX:250 startY:200 withText:standName]; 
    [self drawText:con startX:250 startY:150 withText:standNumber]; 


    CGImageRef cgImage = CGBitmapContextCreateImage(con); 

    UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImage]; 

    NSLog(@"Size is %f", newImage.size.height); 

    return newImage; 

} 

Вершины для моего квадрата являются:

Texutre point is 667.000000 379.000000 
Texutre point is 731.000000 379.000000 
Texutre point is 731.000000 424.000000 
Texutre point is 667.000000 424.000000 

Проблема заключается в том, что в контексте 1000x1000 это, очевидно, привлекает очень маленький форму в правом верхнем углу контекста.

Как я хочу использовать этот UIImage в качестве текстуры, мой вопрос в том, как я могу создать форму нужного размера без каких-либо пробелов (т. Е. Она начинается с 0,0)?

код из Bugivore:

- (UIImage *)drawTexture : (NSArray *)verticesPassed { 

    CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); 

    //This function gets the bounds or smallest rectangle required to generate a shape which 
    //will be used as pattern 
    CGRect shp = [self boundFromFrame:verticesPassed]; 


    //Generate the shape as image so that we can make pattern out of it. 
    CGContextRef conPattern = CGBitmapContextCreate(NULL, 
                shp.size.width, 
                shp.size.height, 
                8, 
                0, 
                rgbColorSpace, 
                (CGBitmapInfo)kCGImageAlphaPremultipliedFirst); 

    CGColorSpaceRelease(rgbColorSpace); 

    CGContextSetLineWidth(conPattern, 10); 
    CGContextSetStrokeColorWithColor(conPattern, [UIColor blueColor].CGColor); 

    Line * start = [verticesPassed objectAtIndex:0]; 
    StandPoint * startPoint = start.origin; 
    CGContextMoveToPoint(conPattern, [startPoint.x floatValue]-shp.origin.x , [startPoint.y floatValue]-shp.origin.y); 

    for (Line * vertice in verticesPassed) { 
     StandPoint * standPoint = vertice.origin; 
     CGContextAddLineToPoint(conPattern, [standPoint.x floatValue]-shp.origin.x, [standPoint.y floatValue]-shp.origin.y); 
    } 

    CGContextStrokePath(conPattern); 

    //Make the main image and color it with pattern. 
    CGImageRef cgImage = CGBitmapContextCreateImage(conPattern); 

    UIImage *imgPattern = [[UIImage alloc]initWithCGImage:cgImage]; 
    //UIImageWriteToSavedPhotosAlbum(imgPattern, nil, nil, nil); 


    UIColor *patternColor = [UIColor colorWithPatternImage:imgPattern]; 

    CGContextRef con = CGBitmapContextCreate(NULL, 
              500, 
              500, 
              8, 
              0, 
              rgbColorSpace, 
              (CGBitmapInfo)kCGImageAlphaPremultipliedFirst); 

    CGColorSpaceRelease(rgbColorSpace); 

    CGContextSetLineWidth(con, 10); 

    CGContextMoveToPoint(con, 0 , 0); 
    CGContextAddLineToPoint(con, 500 , 0); 
    CGContextAddLineToPoint(con, 500, 500); 
    CGContextAddLineToPoint(con, 0 , 500); 


    CGContextSetFillColorWithColor(con, patternColor.CGColor); 

    CGContextFillPath(con); 


    CGImageRef cgImageFinal = CGBitmapContextCreateImage(con); 

    UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImageFinal]; 

    UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil); 

    return newImage; 


} 
-(CGRect)boundFromFrame:(NSArray*)verticesPassed 
{ 
    float top,left,right,bottom; 
    bool bFirst = YES; 

    for (Line * vertice in verticesPassed) { 
     StandPoint * standPoint = vertice.origin; 
     if(bFirst) 
     { 
      left = right = [standPoint.x floatValue]; 
      top = bottom = [standPoint.y floatValue]; 
      bFirst = NO; 
     } 
     else{ 
      if ([standPoint.x floatValue]<left) left = [standPoint.x floatValue]; 
      if ([standPoint.x floatValue]>right) right = [standPoint.x floatValue]; 
      if ([standPoint.x floatValue]<top) top = [standPoint.y floatValue]; 
      if ([standPoint.x floatValue]>bottom) bottom = [standPoint.y floatValue]; 
     } 

    } 

    return CGRectMake(left, top, right - left, bottom-top); 

} 

В фотоальбоме:

enter image description here

+0

Можете ли вы разместить окончательное изображение, как вы хотите, чтобы оно выглядело? Если один и тот же шаблон должен охватывать целое изображение 1000x1000, почему вам нужно было бы передать массив вершин? – Jailbroken

+0

Это класс, который будет обрабатывать различные формы - например, квадрат, треугольники, неправильные формы. Я могу рисовать фигуры, пытаясь создать соответствующие текстуры. – GuybrushThreepwood

+1

получил это - я смогу помочь - я сделал что-то подобное в прошлом. – Jailbroken

ответ

1

Обратите внимание, что я изменил код немного, чтобы проверить его. Но это принимает координаты массива и рисует форму, основанную на строковых координатах. Используется для формирования рисунка над изображением 1000x1000. Заключительное изображение сохраняется в вашем фотоальбоме, чтобы вы могли проверить код. Вы можете заменить его возвратом UIImage в соответствии с вашим исходным кодом. Однако это в первую очередь показывает вам, как вы можете использовать рисунок для создания текстуры.

- (void)drawTexture : (NSArray *)verticesPassed { 

CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); 

//This function gets the bounds or smallest rectangle required to generate a shape which 
//will be used as pattern 
CGRect shp = [self boundFromFrame:verticesPassed]; 


//Generate the shape as image so that we can make pattern out of it. 
CGContextRef conPattern = CGBitmapContextCreate(NULL, 
             shp.size.width, 
             shp.size.height, 
             8, 
             0, 
             rgbColorSpace, 
             kCGImageAlphaPremultipliedFirst); 

CGColorSpaceRelease(rgbColorSpace); 

CGContextSetLineWidth(conPattern, 10); 
CGContextSetStrokeColorWithColor(conPattern, [UIColor blueColor].CGColor); 

Line * start = [verticesPassed objectAtIndex:0]; 
CGContextMoveToPoint(conPattern, start.x-shp.origin.x , start.y-shp.origin.y); 

for (Line * vertice in verticesPassed) { 
    CGContextAddLineToPoint(conPattern, vertice.x-shp.origin.x , vertice.y-shp.origin.y); 
} 
CGContextStrokePath(conPattern); 

//Make the main image and color it with pattern. 
CGImageRef cgImage = CGBitmapContextCreateImage(conPattern); 

UIImage *imgPattern = [[UIImage alloc]initWithCGImage:cgImage]; 
//UIImageWriteToSavedPhotosAlbum(imgPattern, nil, nil, nil); 


UIColor *patternColor = [UIColor colorWithPatternImage:imgPattern]; 

CGContextRef con = CGBitmapContextCreate(NULL, 
             1000, 
             1000, 
             8, 
             0, 
             rgbColorSpace, 
             kCGImageAlphaPremultipliedFirst); 

CGColorSpaceRelease(rgbColorSpace); 

CGContextSetLineWidth(con, 10); 



CGContextMoveToPoint(con, 0 , 0); 
CGContextAddLineToPoint(con, 1000 , 0); 
CGContextAddLineToPoint(con, 1000 , 1000); 
CGContextAddLineToPoint(con, 0 , 10000); 


CGContextSetFillColorWithColor(con, patternColor.CGColor); 

CGContextFillPath(con); 


CGImageRef cgImageFinal = CGBitmapContextCreateImage(con); 

UIImage *newImage = [[UIImage alloc]initWithCGImage:cgImageFinal]; 

UIImageWriteToSavedPhotosAlbum(newImage, nil, nil, nil); 


} 
-(CGRect)boundFromFrame:(NSArray*)verticesPassed 
{ 
float top,left,right,bottom; 
bool bFirst = YES; 

for (Line * vertice in verticesPassed) { 
    if(bFirst) 
    { 
     left = right = vertice.x; 
     top = bottom = vertice.y; 
     bFirst = NO; 
    } 
    else{ 
     if (vertice.x<left) left = vertice.x; 
     if (vertice.x>right) right = vertice.x; 
     if (vertice.x<top) top = vertice.y; 
     if (vertice.x>bottom) bottom = vertice.y; 
    } 

} 

return CGRectMake(left, top, right - left, bottom-top); 

}