How can I use CGContextDrawTiledImage to tile an image?

前端 未结 5 1080
死守一世寂寞
死守一世寂寞 2020-12-05 03:36

I want to be able to an UI object like a UIImageView and tile an image inside of it.

I have been able to use CGContextDrawTiledImage to update the background in the

5条回答
  •  情歌与酒
    2020-12-05 04:24

    I recently did this by creating a custom UIView.

    @interface TiledImageView : UIView {
    @private
        UIImage *image_;
    }
    
    @property (nonatomic, retain) UIImage *image;
    @end
    

    and for the .m file:

    @implementation TiledImageView
    @synthesize image = image_;
    
    - (void)dealloc {
        [image_ release];
        [super dealloc];
    }
    
    - (id)initWithFrame:(CGRect)frame {
        if (self = [super initWithFrame:frame]) {
            // Initialization code
            self.image = [UIImage imageNamed:@"BGTile.png"];
    
        }
        return self;
    }
    
    - (void)drawRect:(CGRect)rect {
        // Drawing code
        CGImageRef image = CGImageRetain(image_.CGImage);
    
        CGRect imageRect;
        imageRect.origin = CGPointMake(0.0, 0.0);
        imageRect.size = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image));
    
        CGContextRef context = UIGraphicsGetCurrentContext();   
        CGContextClipToRect(context, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));  
        CGContextDrawTiledImage(context, imageRect, image);
        CGImageRelease(image);
    }
    
    @end
    

提交回复
热议问题