2012-03-30 52 views
1

我想编写一个例程,这将允许我创建一个UIImage是一个矩形填充渐变背景上的条纹。条纹线出现无处不在

我的代码如下,对大多数情况下我都能正常使用。有趣的是,这是钩子,当我将21作为高度和5作为stripedWidth传递时它不起作用。

一旦我这样做,条纹显示为他们应该...水平..但垂直他们开始在像(y =)-40并结束于约(y =)4左右。为了更好地看到这一点,每张图片都显示了这个问题的效果:

有没有人知道为什么会发生这种情况,甚至更好,我能做些什么呢?

enter image description here

-(UIImage*) stripedTextureWithStartingColor:(UIColor*) startColor withEndingColor:(UIColor*) endColor withHeight:(NSUInteger) height withStripeWidth:(NSUInteger) stripeWidth withStripeColor:(UIColor*) stripedColor { 
    CGSize size = CGSizeMake(2 * stripeWidth, height); 
    UIGraphicsBeginImageContext(size); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSaveGState(context); 
    @try { 
    CGContextSetAllowsAntialiasing(context, true); 
    CGContextSetShouldAntialias(context, true); 
    NSArray* colors = [NSArray arrayWithObjects:(id) startColor.CGColor, (id) endColor.CGColor, nil]; 
    CGFloat locations[2]; 
    locations[0] = 0.0; 
    locations[1] = 1.0; 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef) colors, locations); 
    CGColorSpaceRelease(colorSpace); 
    CGContextDrawLinearGradient(context, gradient, CGPointZero, CGPointMake(0, size.height - 1), 0); 
    CGGradientRelease(gradient); 
    CGContextFillPath(context); 

    int lineWidth = (int) stripeWidth; 
    CGContextSetLineWidth(context, lineWidth/2); 
    int lineCount = (float) size.height/(float) lineWidth; 
    lineCount -= 2; 

    for (int i=0; i<lineCount; i++) { 
     CGContextSetStrokeColorWithColor(context, stripedColor.CGColor); 
     float x1 = -size.height + i * 2 * lineWidth - lineWidth; 
     float y1 = size.height - 1 + lineWidth; 
     float x2 = -size.height + i * 2 * lineWidth + size.height - lineWidth; 
     float y2 = -lineWidth; 
     CGContextMoveToPoint(context, x1, y1); 
     CGContextAddLineToPoint(context, x2, y2); 
     CGContextStrokePath(context); 
    } 

    UIColor* lineTopColor = [[UIColor whiteColor] colorWithAlphaComponent:0.9]; 
    UIColor* lineBottomColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.5]; 

    CGContextSetStrokeColorWithColor(context, lineTopColor.CGColor); 
    CGContextMoveToPoint(context, 0, 0); 
    CGContextAddLineToPoint(context, size.width + 1, 0); 
    CGContextStrokePath(context); 

    CGContextSetStrokeColorWithColor(context, lineBottomColor.CGColor); 
    CGContextMoveToPoint(context, 0, size.height - 1); 
    CGContextAddLineToPoint(context, size.width + 1, size.height - 1); 
    CGContextStrokePath(context); 

    } 
    @finally { 
    CGContextRestoreGState(context); 
    } 
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return image; 
} 

回答

1

发现了它,我的算法是用

+0

你可以张贴究竟是错线的起点稍微不正确的? – 2014-03-03 13:18:29