Skip to content

Instantly share code, notes, and snippets.

@cook
Last active December 13, 2015 19:59
Show Gist options
  • Select an option

  • Save cook/4966907 to your computer and use it in GitHub Desktop.

Select an option

Save cook/4966907 to your computer and use it in GitHub Desktop.
在Quartz 2D中使用pattern。
void drawStripes(void *info, CGContextRef con)
{
// assume 4x4 cell
CGContextSetFillColorWithColor(con, [[UIColor redColor] CGColor]);
CGContextFillRect(con, CGRectMake(0, 2, 4, 2));
CGContextSetFillColorWithColor(con, [[UIColor blueColor] CGColor]);
CGContextFillRect(con, CGRectMake(0, 0, 4, 2));
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// assume the background color is white
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextSaveGState(con);
// punch triangle hole in context clipping region
CGContextMoveToPoint(con, 90, 100);
CGContextAddLineToPoint(con, 100, 90);
CGContextAddLineToPoint(con, 110, 100);
CGContextClosePath(con);
CGContextAddRect(con, CGContextGetClipBoundingBox(con));
CGContextEOClip(con);
// draw the vertical line, add its shape to the clipping region
CGContextMoveToPoint(con, 100, 100);
CGContextAddLineToPoint(con, 100, 19);
CGContextSetLineWidth(con, 20);
CGContextReplacePathWithStrokedPath(con);
CGContextClip(con);
// draw the gradient
CGFloat locs[3] = {0., .5, 1.};
CGFloat colors[12] = {
.3, .3, .3, .8, // starting color
.0,.0,.0,1.0, // intermediate color
.3, .3, .3, .8 // ending color
};
CGColorSpaceRef sp = CGColorSpaceCreateDeviceGray();
CGGradientRef grad = CGGradientCreateWithColorComponents(sp, colors, locs, 3);
CGContextDrawLinearGradient(con, grad, CGPointMake(89, 0), CGPointMake(111, 0), 0);
CGColorSpaceRelease(sp);
CGGradientRelease(grad);
CGContextRestoreGState(con);
// draw the triangle with pattern, the point of the arrow
CGColorSpaceRef sp2 = CGColorSpaceCreatePattern(NULL);
CGContextSetFillColorSpace(con, sp2);
CGColorSpaceRelease(sp2);
CGPatternCallbacks callback = {
0,
&drawStripes, // 绘制函数
NULL // 释放内存的函数
};
CGAffineTransform tr = CGAffineTransformIdentity;
CGPatternRef patt = CGPatternCreate(NULL,
CGRectMake(0, 0, 4, 4), // pattern cell's size
tr,
4, 4, // 相邻pattern的origin point的间隔
kCGPatternTilingConstantSpacingMinimalDistortion,
true, // if use color
&callback); // 绘制函数
CGFloat alph = 1.0;
CGContextSetFillPattern(con, patt, &alph);
CGPatternRelease(patt);
CGContextMoveToPoint(con, 80, 25);
CGContextAddLineToPoint(con, 100, 0);
CGContextAddLineToPoint(con, 120, 25);
CGContextFillPath(con);
}
@cook
Copy link
Author

cook commented Feb 16, 2013

和draw-arrow-with-gradient.mm唯一的差别是将CGContextSetFillColorWithColor(...)句替换成了和pattern有关的若干条语句。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment