【问题标题】:Could someone please show me how to create a CGPattern that I can use to stroke a path with an image?有人可以告诉我如何创建一个CGPattern,我可以用它来用图像描边路径吗?
【发布时间】:2010-03-03 16:30:51
【问题描述】:

我想使用我拥有的 .png 来描边路径,但我只是不知道如何制作 CGPatternRef。

【问题讨论】:

    标签: iphone core-graphics cgcontext


    【解决方案1】:

    这里有一个小sn-p

    - (void)drawRect:(CGRect)rect
    {
        CGContextRef context = UIGraphicsGetCurrentContext();
        [self patternMake2:rect context:context];
    }
    //-------------------------------------------------------------------
    //      patternMake2
    //-------------------------------------------------------------------
    void pattern2Callback (void *info, CGContextRef context) {      
        UIImage *image = [UIImage imageNamed:@"NavBarBg.png"];
        CGImageRef imageRef = [image CGImage];
        CGContextDrawImage(context, CGRectMake(0, 0, 320, 44), imageRef);
    }
    
    
    - (void)patternMake2:(CGRect)rect context:(CGContextRef)context
    {
        static const CGPatternCallbacks callbacks = { 0, &pattern2Callback, NULL };
        //NSLog(@"rect: %f %f %f %f", rect.origin.x, rect.origin.x, rect.size.width, rect.size.height); 
        //CGContextSaveGState(context);
        CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL);
        CGContextSetFillColorSpace(context, patternSpace);
        CGColorSpaceRelease(patternSpace);
        CGSize patternSize = CGSizeMake(315, 44);
        CGPatternRef pattern = CGPatternCreate(NULL, self.bounds, CGAffineTransformIdentity, patternSize.width, patternSize.height, kCGPatternTilingConstantSpacing, true, &callbacks);
        CGFloat alpha = 1;
        CGContextSetFillPattern(context, pattern, &alpha);
        CGPatternRelease(pattern);
        CGContextFillRect(context, rect);       
        //CGContextRestoreGState(context);
    }
    

    【讨论】:

    • 我们应该总是将 NULL 传递给 info 吗?
    【解决方案2】:

    参见the relevant chapter of the Quartz 2D Programming Guidethe reference documentation for CGPattern

    在“LOOK PRETTY PATTERNS”一页又一页的编程指南中隐藏的基本细节是,您需要编写一个回调函数来绘制该模式的一个实例,并将指向该回调的指针传递给CGPatternCreate .当您绘制图案时,Quartz 将调用您的回调,然后平铺您绘制的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 2021-11-16
      • 2014-11-25
      • 2011-03-10
      • 2011-06-21
      相关资源
      最近更新 更多