How can I use CGContextDrawTiledImage to tile an image?

前端 未结 5 1082
死守一世寂寞
死守一世寂寞 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:01

    Rather than trying to modify a UIImageView, consider subclassing UIView instead. UIImageView is specifically designed for one non-tiled image and some of the internals may be messing you up. It's not really intended to be modified in the way you describe.

    In a subclass of UIView (UITiledImageView?) you can use the drawRect: method to do what you want. You can even create ivars for the image, its size and tiling properties for greater flexibility and extensibility.

    Updated with sample project: http://github.com/kailoa/6tringle-tiledimageview/tree/master

    The relevant drawing code:

    - (void)drawRect:(CGRect)rect 
    {
        if (TiledImage) {
    
            //Since we are retaining the image, we append with ret_ref.  this reminds us to release at a later date.
            CGImageRef image_to_tile_ret_ref = CGImageRetain(TiledImage.CGImage); 
    
            CGRect image_rect;
            image_rect.size = TiledImage.size;  //This sets the tile to the native size of the image.  Change this value to adjust the size of an indivitual "tile."
    
            CGContextRef context = UIGraphicsGetCurrentContext();
    
            CGContextDrawTiledImage(context, image_rect, image_to_tile_ret_ref);
    
            CGImageRelease(image_to_tile_ret_ref);
        }
    }
    

提交回复
热议问题