Drawing NSString to UIImage

前端 未结 4 1744
梦毁少年i
梦毁少年i 2021-01-25 04:54

I have a NSString object. I want to write it to existing UIImage object. UIImage object already has some image associate with it. I want to write string to same image. How do i

4条回答
  •  情话喂你
    2021-01-25 05:18

    Here is my code. I have a 35x480 View and I draw text rotated by 90 degrees on it. I hope this helps. I draw the Image and then the text so it shows up. It looks like a window's window title.

    I draw the image then the text on the drawRect.

    @synthesize topView;
    @synthesize delegate;
    
    - (id)initWithFrame:(CGRect)frame
    {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
        topView.backgroundColor = [UIColor clearColor];
        topView.opaque = NO;
    
    
        }
        return self;
    }
    
    
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    - (void)drawRect:(CGRect)rect
    {
        UIGraphicsBeginImageContext(img.image.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSaveGState(context);
    
        // draw titleborder
        CGRect titleRect = CGRectMake(0, 0, 35, 480);
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"titleborder" ofType:@"png"];  
        UIImage *titleImage = [[UIImage alloc] initWithContentsOfFile:filePath];
        [titleImage drawInRect:titleRect];
        [self bringSubviewToFront:topView];
    
        UIFont *font = [UIFont boldSystemFontOfSize:16.0];
    
        CGRect textRect = CGRectMake(0, rect.size.height/2, 480, 40);
        NSLog(@"text rect frame: %@", NSStringFromCGRect(textRect));
    
        [self drawText:[[NSString alloc] initWithFormat:@"My Window Title"] rect:textRect context:context font:font red:1.0 green:1.0 blue:1.0 alpha:1.0] ;
    
        CGContextRestoreGState(context);
    
    
    }
    
    - (void) drawText: (NSString *)text rect: (CGRect)rect context:(CGContextRef)context font:(UIFont *)font red:(CGFloat)r green: (CGFloat)g blue:(CGFloat)b alpha:(CGFloat)alpha {
        CGContextSetTextDrawingMode(context, kCGTextFill);
    
        CGContextSetRGBFillColor(context, r, g, b, alpha); // 6 
        CGContextSetRGBStrokeColor(context, 1, 1, 1, 1);
        CGAffineTransform transform1 = CGAffineTransformMakeRotation(-90.0 * M_PI/180.0);
        CGContextConcatCTM(context, transform1);
    
        CGSize sizeOfString = [text sizeWithFont:font];
        CGContextTranslateCTM(context, (sizeOfString.width/2) - 420,-232);
    
        [text drawInRect:rect withFont:font lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentLeft];
    }
    

提交回复
热议问题