【问题标题】:cropping an area CGRect from UIGraphicsImageContext从 UIGraphicsImageContext 裁剪区域 CGRect
【发布时间】:2015-10-28 22:39:30
【问题描述】:

我在当前视图的CGContext 中绘制了一个形状像箭头的CGPath。我想生成箭头的微型版本(缩略图),以将其作为Image 添加到显示所有选定箭头的UITableView

我成功地缩小了完整上下文的图片,使箭头小于应有的大小。理想情况下,我想将完整上下文的图像裁剪到箭头的范围内。然而,我还没有成功。有什么线索吗?感谢您的帮助!

这是包含箭头的完整视图图片和我正在生成的缩略图的另一张图片。

理想情况下,上面的缩略图将被裁剪为仅包含箭头 - 而不是完整的上下文。

我使用的代码如下:

- (UIImage*) imageForObject:(id<GraphicalObject>) object 
                     inRect:(CGRect)rect {

    UIImage *image = [UIImage new];
    CGRect objectBounds = [object objectBounds];
    UIGraphicsBeginImageContext(self.view.frame.size);//objectBounds.size);
    CGContextRef context =UIGraphicsGetCurrentContext();
    [object drawInContext:context];
    //doesn't work 
    CGContextClipToRect(context, objectBounds);

    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

【问题讨论】:

    标签: ios objective-c crop cgcontextref downsize


    【解决方案1】:

    称为objectBoundsCGRect 有两个组件,一个origin 和一个size。为了将对象正确绘制为缩略图,代码需要缩放图像(以获得正确的大小)并转换图像(将原点移动到{0,0})。所以代码是这样的

    - (UIImage *)getThumbnailOfSize:(CGSize)size forObject:(UIBezierPath *)object
    {
        // to maintain the aspect ratio, we need to compute the scale
        // factors for x and y, and then use the smaller of the two
        CGFloat xscale = size.width / object.bounds.size.width;
        CGFloat yscale = size.height / object.bounds.size.height;
        CGFloat scale = (xscale < yscale) ? xscale : yscale;
    
        // start a graphics context with the thumbnail size
        UIGraphicsBeginImageContext( size );
        CGContextRef context = UIGraphicsGetCurrentContext();
    
        // here's where we scale and translate to make the image fit
        CGContextScaleCTM( context, scale, scale );
        CGContextTranslateCTM( context, -object.bounds.origin.x, -object.bounds.origin.y );
    
        // draw the object and get the resulting image
        [object stroke];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return image;
    }
    

    【讨论】:

    • 谢谢 - 这适用于 cgpath - 但是我仍然需要用渐变填充它。
    • @user1612877 使用[object drawInContext:context] 而不是[object stroke]。我使用简单的UIBezierPath 进行测试,因为我没有绘制箭头的代码。
    • 谢谢 - 这对我有用。为了方便起见,我想说的是,在绘制箭头时,我必须区分四种情况,根据箭头指向的象限,CGContextTranslateCTM() 函数的最后两个参数需要在 0/- 的所有可能组合之间进行更改objectBounds.origin.x, 0/-objectBounds.origin.y
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 2020-11-19
    • 2014-03-17
    • 2013-08-11
    相关资源
    最近更新 更多