Как программно сгенерировать UIImage с помощью Quartz 2D и Grand CEntral Dispatch - PullRequest
2 голосов
/ 05 февраля 2012

Прямо сейчас у меня есть изображение, которое генерируется одним касанием программно с помощью Quartz 2D.Я хотел использовать его в сочетании с грандиозной центральной диспетчеризацией, чтобы его можно было создать на другом процессоре и запускать обычную анимацию постепенного исчезновения после его завершения.Прямо сейчас я использую следующий код в нижней части этого поста, но я получаю эти недопустимые ошибки контекста.Есть ли способ сделать это, или мне не повезло?

CGContextTranslateCTM: недопустимый контекст 0x0 CGContextScaleCTM: недопустимый контекст 0x0 CGContextSaveGState: недопустимый контекст 0x0 CGContextSetCompositeOperation: недопустимый контекст 0x0C0RTGTContext: Conject Conjectневерный контекст 0x0 CGContextDrawImage: неверный контекст 0x0

мой код:

    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
        self.view.contentScaleFactor=[[UIScreen mainScreen] scale];
        CGSize sizeofText=[stopName sizeWithFont:[UIFont fontWithName:@"Helvetica-Bold" size:17.5*[self.view contentScaleFactor]]];
        CGSize size;
        size.width=1024;
        size.height=1024;

        UIImage *leftCap = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"leftcap@2x" ofType:@"png"]];
        UIImage *center = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"center@2x" ofType:@"png"]];
        UIImage *rightCap = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"rightcap@2x" ofType:@"png"]];
        UIImage *spike = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"spike@2x" ofType:@"png"]];
        UIGraphicsBeginImageContextWithOptions(size,false,0);

        CGContextRef context = UIGraphicsGetCurrentContext(); //get the context we just made above
        CGContextTranslateCTM(context, 0,size.height);
        CGContextScaleCTM(context, 1, -1);

        width=(19*[self.view contentScaleFactor])+(sizeofText.width)+(43*[self.view contentScaleFactor]);

        height=60*[self.view contentScaleFactor];

        //draw calls
        [leftCap drawInRect:CGRectMake(0,1024- 54.0f*[self.view contentScaleFactor], 19.0f*[self.view contentScaleFactor], 54.0f*[self.view contentScaleFactor])];    
        [center drawInRect:CGRectMake(19.0f*[self.view contentScaleFactor],1024- 54.0f*[self.view contentScaleFactor],(sizeofText.width), 54.0f*[self.view contentScaleFactor])];
        [rightCap drawInRect:CGRectMake((sizeofText.width)+19*[self.view contentScaleFactor],1024- 54.0f*[self.view contentScaleFactor], 43.0f*[self.view contentScaleFactor], 54.0f*[self.view contentScaleFactor])];
        [spike drawInRect:CGRectMake((width/2)-((32.0f*[self.view contentScaleFactor])/2.0f),1024-(43.5*[self.view contentScaleFactor])- 27.0f*[self.view contentScaleFactor], 32.0f*[self.view contentScaleFactor], 27.0f*[self.view contentScaleFactor])];

        CGContextSelectFont(context, "Helvetica-Bold", 17.5*[self.view contentScaleFactor], kCGEncodingMacRoman);
        CGContextSetTextDrawingMode(context, kCGTextFill);
        CGContextSetTextPosition(context,19.f*[self.view contentScaleFactor],1024- (7.5*[self.view contentScaleFactor])-(sizeofText.height));
        CGContextShowText(context, [stopName UTF8String], strlen([stopName UTF8String]));

        image=UIGraphicsGetImageFromCurrentImageContext();



        UIGraphicsEndImageContext();

    });



    dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
        NSLog(@"done. I would trigger the fade in animation ehre"); 
    });

1 Ответ

4 голосов
/ 05 февраля 2012

Я делаю нечто подобное, за исключением того, что я использую CGBitmapContextCreate вместо UIGraphicsBeginImageContextWithOptions. Похоже, ваш контекст не создается - возможно, потому, что вы вызываете функцию пользовательского интерфейса * в фоновом потоке.

CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();

CGContextRef _composedImageContext = CGBitmapContextCreate(NULL, 
                                              width, 
                                              height, 
                                              8, 
                                              width*4, 
                                              rgbColorSpace, 
                                              kCGImageAlphaPremultipliedFirst);

CGColorSpaceRelease( rgbColorSpace );


// draw your things into _composedImageContext

//finally turn the context into a CGImage
CGImageRef cgImage = CGBitmapContextCreateImage(_composedImageContext);
...