Search code examples
iosswiftcalendaruiimageuicolor

create UIImage to be a border with color


I am using FSCalendar What I want to do is change the way of showing events. I want to put a coloured rectangle border around the cell with events. I did that by editing the cell background layer and worked fine, but now I realized that it is the wrong place to put my code as updating to the latest version of FSCalendar which will override my changes. One of what I can access by the calendar delegates is to set image to the cell, So I want to create image as rectange border with the event colour. Here is an image of what I want: Calendar With events as rectangle border

Any suggessions is appreicated. Thanks in advance.


Solution

  • This method will draw a bordered rectangle. I would make it class method and put into UIImage category for convenient use.

    - (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)imageSize andBorderWidth:(CGFloat)borderWidth fillWithColor:(BOOL)fillWithColor{
    
        UIGraphicsBeginImageContext(imageSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        CGRect rect = CGRectMake(0, 0, imageSize.width, imageSize.height);
    
        if(fillWithColor) {
            [color setFill];
            CGContextFillRect(context, rect);
        } else {
            [color setStroke];
            CGContextStrokeRectWithWidth(context, rect, borderWidth);
        }
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    

    EDIT: Added fillWithColor parameter