Can someone please show me how to create a CGPattern that I can use to pat the image path?

I want to pat the path using the .png I have, but I just don't know how to make CGPatternRef.

+3
source share
2 answers

See the relevant chapter on two-dimensional quartz programming and the reference documentation for CGPattern .

The important detail that was laid out in the Programming Guide on the LOOK PRETTY PATTERNS pages and pages is that you need to write a callback function that draws one instance of the template and passes a pointer to this callback to CGPatternCreate, When you draw the template , Quartz will call your callback, and then lay out everything you drew.

+4
source

here is a small fragment

- (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);
}
+6
source

Source: https://habr.com/ru/post/1735273/


All Articles