【问题标题】:iOS : Repositioning UIGraphicsBeginImageContext and UIImageViewiOS:重新定位 UIGraphicsBeginImageContext 和 UIImageView
【发布时间】:2026-01-24 20:05:02
【问题描述】:

我有代码可以让我在 UIImageView 上绘图 - 但我希望能够限制绘图区域。

我已经能够限制大小,但现在我无法定位它:如果我将 (0, 0) 更改为其他任何内容,我的图像就会完全消失并且绘图功能停止工作

drawImage - 是一个 UIImageView

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    mouseSwiped = YES;

    UITouch *touch = [touches anyObject];
    currentPoint = [touch locationInView:self];

    UIGraphicsBeginImageContext(CGSizeMake(560, 660));
    [drawImage.image drawInRect:CGRectMake(0, 0, 560, 660)];

    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 0, 1, 0, 1);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());

    [drawImage setFrame:CGRectMake(0, 0, 560, 660)];
    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    lastPoint = currentPoint;

    [self addSubview:drawImage];
} 

非常感谢任何帮助

【问题讨论】:

    标签: ios objective-c uiimageview core-graphics cgcontext


    【解决方案1】:

    我不确定我是否完全理解你想要做什么,但我会尝试一下:

    [drawImage.image drawInRect:CGRectMake(0, 0, 560, 660)];
    

    这告诉分配给drawImage 的图像在0,0 的当前上下文中绘制自己。由于上下文是位图图像上下文,其范围将从0,0560,660。在我看来,这可能是您想要做的,否则您的位图中会有空白区域。如果您要将 0,0 更改为 10,0,我希望生成的位图中会有一个 10pt 宽的空白区域(这似乎是一种浪费)。

    然后你再这样做:

    [drawImage setFrame:CGRectMake(0, 0, 560, 660)];
    

    这是在其父视图的坐标系中设置 UIImageView 的坐标。如果您将 那个 0,0 更改为 5,5 我希望您的 UIImageView 在其超级视图中显示为向下 5pt 和向右 5pt。

    你说你想“限制绘图区域”。我假设您的意思是您在图像上绘制的部分。最简单的方法是在绘制之前在位图上下文中设置一个剪辑矩形。例如,如果您想防止在图像边缘周围绘制 10pt 带,您可以这样做:

    UIGraphicsBeginImageContext(CGSizeMake(560, 660));
    [drawImage.image drawInRect:CGRectMake(0, 0, 560, 660)];
    
    CGContextClipToRect(UIGraphicsGetCurrentContext(), CGRectMake(10,10,540,640));
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    // ... and so on
    

    不是 100% 确定这是否是您正在寻找的东西,但希望它会有所帮助。

    【讨论】:

    • 非常感谢解释:
    【解决方案2】:

    尝试限制currentPoint

    if (currentPoint.x <= 20 || currentPoint.x >= 280 || 
        currentPoint.y <= 20 || currentPoint.y >= 400)
    {
        lastPoint = currentPoint;
        return;
    }
    

    【讨论】: