条纹线无处不在

时间:2012-03-30 15:11:31

标签: ios uiimage core-graphics

我正在尝试编写一个例程,允许我创建一个UIImage,它是一个在渐变背景上填充条纹的矩形。

我的代码在下面,并且在我尝试过的大多数情况下都能正常工作。有趣的是,这是钩子,当我将它作为高度传递21和将条带宽度传递为5时,它不起作用。

一旦我这样做,条纹就会出现......它们应该......水平地......但是它们垂直地从(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 :(得分:1)

找到它,我的算法在行开始时略有不正确