为方法创建渐变和返回

为方法创建渐变和返回

本文介绍了为方法创建渐变和返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉有关iPhone和Quartz编程的愚蠢问题。刚刚开始从C ++转换为Objective-C:)

Sorry for noobish question about iPhone and Quartz programming. Just started my conversion from C++ to Objective-C :)

所以,我有这样的类方法

So, I have such a class method

+(CGGradientRef)CreateGradient:(UIColor*)startColor endColor:(UIColor*)endColor
{
    CGGradientRef result;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGFloat locations[2] = {0.0f, 1.0f};
    CGFloat startRed, startGreen, startBlue, startAlpha;
    CGFloat endRed, endGreen, endBlue, endAlpha;

    [endColor getRed:&endRed green:&endGreen blue:&endBlue alpha:&endAlpha];
    [startColor getRed:&startRed green:&startGreen blue:&startBlue alpha:&startAlpha];

    CGFloat componnents[8] = {
        startRed, startGreen, startBlue, startAlpha,
        endRed, endGreen, endBlue, endAlpha
    };
    result = CGGradientCreateWithColorComponents(colorSpace, componnents, locations, 2);
    CGColorSpaceRelease(colorSpace);
    return result;
}

及其使用情况。

-(void)FillGradientRect:(CGRect)area startColor:(UIColor *)startColor endColor:(UIColor *)endColor isVertical:(BOOL)isVertical
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    CGGradientRef gradient = [Graphics CreateGradient:startColor endColor:endColor];

    CGPoint startPoint, endPoint;
    if (isVertical) {
        startPoint = CGPointMake(CGRectGetMinX(area), area.origin.y);
        endPoint = CGPointMake(startPoint.x, area.origin.y + area.size.height);
    }else{
        startPoint = CGPointMake(0, area.size.height / 2.0f);
        endPoint = CGPointMake(area.size.width, startPoint.y);
    }

    CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);

    CGGradientRelease(gradient);
    UIGraphicsPopContext();
}

一切都按预期工作。但是,当我从Xcode 4运行Analyze工具时,我收到一个关于 CreateGradient 结果变量的内存泄漏的警告。好吧,我理解那是什么,但在我的调用方法中,我正在释放渐变对象( CGGradientRelease(gradient); )。
那么,谁错了,如何让Analyze工具开心?

everything works as expected. But, when I run the Analyze tool from Xcode 4, I'm getting a warning about memory leak in method CreateGradient for result variable. Well, I understand what's that about, but in my calling method I'm releasing the gradient object (CGGradientRelease(gradient);).So, who is wrong and how to make Analyze tool happy?

Thx

推荐答案

由于CGGradientRef是Core Foundation类型的对象,你可以自动发布它。只需在返回渐变之前添加此行:

Since CGGradientRef is a Core Foundation type of object, you can autorelease it. Just add this line before returning the gradient:

[(id)result autorelease];

这篇关于为方法创建渐变和返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:54