【问题标题】:Changing line width of CGContext while changing the image colour?在更改图像颜色时更改 CGContext 的线宽?
【发布时间】:2013-06-16 21:25:09
【问题描述】:

我正在尝试更改使用 CG 绘制的矩形的宽度和颜色。在下面的函数中,我用不同的颜色遮盖了图像,但是如何更改宽度?

- (void)colorImage:(UIImage *)origImage withColor:(UIColor *)color withWidth:(float) width
{
UIImage *image = origImage;
NSLog(@"%f", width);
CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, width);
CGContextClipToMask(context, rect, image.CGImage);
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImage *flippedImage = [UIImage imageWithCGImage:img.CGImage
                                            scale:1.0 orientation:          UIImageOrientationDownMirrored];

self.image = flippedImage;
}

【问题讨论】:

    标签: ios core-graphics


    【解决方案1】:

    你用CGContextSetLineWidth(context, width)设置线宽。

    您没有看到任何效果的原因是因为您没有抚摸任何东西。线宽适用于通过描边绘制的线条。您是在填充,而不是在抚摸,并且填充没有可赋予宽度的线条。

    如果要在矩形周围添加边框,则需要对其进行描边。这就是在某个形状的周边画一条线的原因。

    您有三个选择:

    • 拨打CGContextSetLineWidth,然后拨打CGContextStrokeRect
    • 致电CGContextStrokeRectWithWidth
    • 调用CGContextSetLineWidth,然后调用CGContextAddRect(将矩形添加到当前路径),然后调用CGContextDrawPathkCGPathFillStroke。 (如果您愿意,也可以在SetLineWidth 之前调用AddRect——它们只需要在DrawPath 之前发生即可。)

    请注意,笔划以路径轮廓为中心,因此一半在路径/矩形内部,一半在外部。如果你的线条是 1 像素宽,这将显示为半透明的线条(因为没有其他方法可以表示“半像素”)。如果您的线条是偶数个像素宽,并且您划过上下文(或视图)的整个边界,您将只能看到内部线条的一半。

    您还应该决定是否真的要填充,或者是否只需要描边。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-29
      • 2018-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多