【问题标题】:Adding border around an UIImage在 UIImage 周围添加边框
【发布时间】:2014-09-12 04:42:15
【问题描述】:

我正在使用下面的代码为相机胶卷中的选定图像添加文本和边框。

-(UIImage*)image:(UIImage*)image withText:(NSString*)text atPoint:(CGPoint)point{
if (text) {
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    [image drawInRect:rect];

    NSDictionary *attributes = @{NSFontAttributeName           : [UIFont boldSystemFontOfSize:80],
                                 //NSStrokeWidthAttributeName    : @(4),
                                 NSStrokeColorAttributeName    : [UIColor whiteColor]};
    [text drawAtPoint:point withAttributes:attributes];

    CALayer *l = [self.imageView layer];
    [l setBorderWidth:10.0];
    [l setBorderColor:[[UIColor blueColor] CGColor]];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();    
}
return newImage;
}

当我在我的应用程序中单击保存按钮时,我将编辑后的图像保存到相机胶卷。但相机胶卷内的编辑图像只有文本,没有任何添加边框。我是否在上面的代码中遗漏了添加和保存图像边框的任何内容?除了CALayer还有什么其他的方法可以加边框吗?

【问题讨论】:

  • 您正在为 imageView 的图层添加边框,而应该在图像上下文中绘制。
  • @Keenle 我没听懂你。你能用代码让我理解吗?
  • UIImage 是一个最终包含位和字节的结构。您可以将图像发送到 peed、将其存储到磁盘或在屏幕上显示。 CALayer 是一个核心动画层,与UIView 非常相关,专门用于显示。简而言之,更改显示层的属性不会对您的图像产生永久影响。 @Keenle 代码实际上在您的图像中绘制,有效地修改它。
  • 根据问题:Whether i am missing anything in above code to add and save border around image?我正在修改图片。

标签: ios objective-c ios7 uiimageview uiimage


【解决方案1】:

我将回复“在 UIView 中在 UIImage 周围添加边框”

从目前来看,最简单的方法是在视图层次结构中插入另一个视图。

[self.view insertSubview:({
    UIView * border = [[UIView alloc]
        initWithFrame:CGRectInset(self.imageView.frame, -1, -1)];
    border.backgroundColor = [UIColor blueColor];

    border;
})
belowSubview:self.imageView];

【讨论】:

    【解决方案2】:

    替换这个:

    CALayer *l = [self.imageView layer];
    [l setBorderWidth:10.0];
    [l setBorderColor:[[UIColor blueColor] CGColor]];
    

    有了这个:

    UIBezierPath *rectangleBezier = [UIBezierPath bezierPathWithRect:rect];
    rectangleBezier.lineWidth = 20.0f; // 10 * 2 because line drawn from the center of edge
    [[UIColor blueColor] setStroke];
    [rectangleBezier stroke];
    

    备注: CALayer *l = [self.imageView layer]; 与 UIImage 数据无关。 imageView 的 layer 改变 imageView 的表现。不是 UIImage 的内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多