Search code examples
iosobjective-cuicolor

Write in rectangle and fill it with a color


I want to draw a rectangle, fill the rectangle with a chosen color from a palette and then write into it. I am able to draw and write into it but when I fill the rectangle, the written text gets covered. and I can't see anything. I am Developing a minesweeper game in IOS and setting cell colors for Opened and closed cells.

        UIFont *font = [UIFont systemFontOfSize: .75*self.dh];
        for(int i = 0 ; i < 16; i ++){
            for(int j = 0;j < 16;j ++){
                if(mineMatrix[i][j] == -2 || mineMatrix[i][j] == -4){
                    //                    NSString *mine = @"F";
                    //                    CGPoint xy = { (i+0.17)*self.dw, j*self.dh};
                    //                    [mine drawAtPoint: xy withFont: font];


                    // establish bounding box for image
                    CGPoint tl = { (i)*self.dw, j*self.dh + 103};
                    CGRect imageRect = CGRectMake(tl.x, tl.y, dw, dh);

                    // place appropriate image where dragging stopped
                    UIImage *img;
                    img = [UIImage imageNamed:@"flags.png"];
                    [img drawInRect:imageRect];


                }else{
                    CGPoint tl = { (i)*self.dw, j*self.dh + 103};
                    CGRect imageRect = CGRectMake(tl.x, tl.y, dw, dh);
                    CGContextRef context = UIGraphicsGetCurrentContext();
                    CGContextSetFillColorWithColor(context, [UIColor redColor].CGColor);
                    CGContextFillRect(context, imageRect);
                }
                if(mineMatrix[i][j] != -3 && mineMatrix[i][j] != 0 && mineMatrix[i][j] != -2 && mineMatrix[i][j] != -1 && mineMatrix[i][j] != -4){
                    NSString *mine = [[NSNumber numberWithInt: mineMatrix[i][j]] stringValue];
                    CGPoint xy = { (i+0.17)*self.dw, j*self.dh + 103};
                    [mine drawAtPoint: xy withFont: font];
                }
                if(mineMatrix[i][j] == 0 || mineMatrix[i][j] == -1){
                    UIImage *img;
                    CGPoint tl = { (i)*self.dw, j*self.dh + 103};
                    CGRect imageRect = CGRectMake(tl.x, tl.y, dw, dh);
                    [img drawInRect:imageRect];
                }


            }

        }

    }

Solution

  • The problem is that by the time you draw the text, you have already set the fill color of the context in order to draw the background. So then the text is drawn in the same color as the background and you don't see anything.

    So just change the fill color to something else just before drawing the text, like this:

    [[UIColor blackColor] set]; // or whatever color you like
    [mine drawAtPoint: xy withFont: font];
    

    Or, even better, draw attributed text that has its own color.