【问题标题】:Setting CPView frame so that it encases drawn rect设置 CPView 框架使其包含绘制的矩形
【发布时间】:2013-12-17 18:43:39
【问题描述】:

我在 Cappuccino 中的目标是调整 CPView 的框架,以便将绘制的矩形的每个点都包含在内。矩形是可旋转的,这使得它很棘手:
(来源:asawicki.info
.

我知道在 Cocoa 中我会使用 CGContextGetClipBoundingBox(context)。 在 Cappuccino 中我该如何处理这样的问题?

编辑:根据 Alexander 的提示,这就是我的问题的答案:

var context = [[CPGraphicsContext currentContext] graphicsPort],
    transform = CGAffineTransformRotate(CGAffineTransformMakeTranslation(CGRectGetWidth([self bounds])/2, CGRectGetHeight([self bounds])/2), rotationRadians);

CGContextBeginPath(context);
path2 = CGPathCreateMutable();
CGPathAddRect(path2, transform, CGRectMake(-newWidth/2, -newHeight/2, newWidth, newHeight));
CGContextAddPath(context, path2);
CGContextClosePath(context);
CGContextSetFillColor(context, [CPColor yellowColor]);
CGContextFillPath(context);

CGContextRestoreGState(context);

var frame = [self frame];
frame.size.width = CGRectGetWidth([self bounds]);
frame.size.height =  CGRectGetHeight([self bounds]);
oldFrameWidth = frame.size.width;
oldFrameHeight = frame.size.height;
newFrameWidth = CGRectGetWidth(CGPathGetBoundingBox(path2));
newFrameHeight = CGRectGetHeight(CGPathGetBoundingBox(path2));
frame.size.width = newFrameWidth;
frame.size.height = newFrameHeight;
frame.origin.x -= (newFrameWidth - oldFrameWidth)/2;
frame.origin.y -= (newFrameHeight - oldFrameHeight)/2;
[self setFrame:frame];

【问题讨论】:

    标签: objective-c cocoa cappuccino objective-j


    【解决方案1】:

    如果myPath 是描述旋转矩形的CGPath,则可以使用以下方法获取边界矩形:

    CGPathGetBoundingBox(myPath)
    

    【讨论】:

    • Alex,我目前有边界 CPView 的正确尺寸(参见上面的代码),但绘制的矩形的中心位于 CPView 的左上角。如何将它带到 CPView 的中心?
    • 那是因为您正在以这种方式绘制矩形,位于 (-newWidth/2, -newHeight/2)。如果您想将其绘制在中心,则可以将平移添加到边界宽度和高度的一半的变换中。
    • 谢谢。如何在不覆盖旋转的情况下将平移添加到变换中?
    • 您可以“组合”多个转换,如下所示:transform = CGAffineTransformTranslate( CGAffineTransformMakeRotation(rotationRadians), newWidth / 2, newHeight / 2))
    • 谢谢,使用上面的代码,我没有进一步了解,因为绘制的矩形的左上角正好匹配边界 CPView 的左上角。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多