开发者社区> 问答> 正文

在iOS 13中在图像上绘制文本?

我正在尝试在UISlider缩略图上绘制图像和一些文本。我有以下代码在iOS 12及以下版本上正常运行,但在iOS 13及以上版本(特别是iOS 13.2)上无效。


  CGFloat scale = 5.0;
  //Drawing BG Image
  // Where bg image is some image on top of which i need to render text. 
  UIGraphicsBeginImageContextWithOptions(CGSizeMake(bgImage.size.width * scale, bgImage.size.height * scale), NO, 1);

  // This works
  [bgImage drawInRect:CGRectMake(0, 0, bgImage.size.width * scale, bgImage.size.height * scale)];


  CGRect valueBgRect;
  UIColor * textColor;
  UIFont * textFont;

  textColor = [UIColor whiteColor];
  valueBgRect = CGRectMake(18,40, bgImage.size.width,bgImage.size.height);
  textFont = [UIFont fontWithName:@"Helvetica-Bold" size:50];

  NSDictionary *attrsValue = @{ NSForegroundColorAttributeName : textColor,
                         NSFontAttributeName            : textFont,
                         NSTextEffectAttributeName      : NSTextEffectLetterpressStyle};
  // This doesn't.
  [value drawInRect:valueBgRect withAttributes:attrsValue];
  // Though I can see the image, the text that should be on top of it is not visible. 
  UIImage *theImage=UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return theImage; }

我也尝试在UILabel上设置文本并使用

和```[self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];

但是都没有作用。

展开
收起
南南唐语 2019-12-03 21:06:07 1044 0
1 条回答
写回答
取消 提交回答
  • 在IOS 13 上工作:```_imgView.image = [self drawFront:[UIImage imageNamed:@"chain_image.jpeg"] text:@"SANKET VAGHELA" atPoint:CGPointMake(50, 50)];

    打开function```   -(UIImage*)drawFront:(UIImage*)image text:(NSString*)text atPoint: 
       (CGPoint)point
    {
        UIFont *font = [UIFont systemFontOfSize:20];
        UIGraphicsBeginImageContext(image.size);
        [image drawInRect:CGRectMake(0,0,image.size.width,image.size.height)];
        CGRect rect = CGRectMake(point.x, (point.y - 5), image.size.width, image.size.height);
        [[UIColor whiteColor] set];
    
        NSMutableAttributedString* attString = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange range = NSMakeRange(0, [attString length]);
    
        [attString addAttribute:NSFontAttributeName value:font range:range];
        [attString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range];
    
        NSShadow* shadow = [[NSShadow alloc] init];
        shadow.shadowColor = [UIColor darkGrayColor];
        shadow.shadowOffset = CGSizeMake(1.0f, 1.5f);
        [attString addAttribute:NSShadowAttributeName value:shadow range:range];
    
        [attString drawInRect:CGRectIntegral(rect)];
        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    
    2019-12-03 21:17:58
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载