OGeek|极客世界-中国程序员成长平台

标题: iOS - 父/ subview 的 Quartz 绘图问题 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 13:34
标题: iOS - 父/ subview 的 Quartz 绘图问题

场景

我有两种观点。一种是“父” View ,其中包含一个“子” View ,用于绘图。我在后面的代码中将 child 称为 QuartzView。 QuartzView 知道如何根据自己的上下文绘制正方形。

问题

当我告诉它的 self 上的 QuartzView 绘制一个正方形时,它会按预期进行。当我使用父 View 告诉 QuartsView 在它的 self 上绘制一个正方形时,它会在屏幕左下角以预期大小的 1/5 左右绘制正方形。

问题

我认为这里存在一些父/子或上下文问题,但我不确定它们是什么。如何让两个正方形以完全相同的大小在完全相同的位置绘制?

ViewController

- (void)drawASquare {

    // this code draws the "goofy" square that is smaller and off in the bottom left corner
    x = qv.frame.size.width / 2;
    y = qv.frame.size.height / 2;
    CGPoint center = CGPointMake(x, y);
    [qv drawRectWithCenter:center andWidth:50 andHeight:50 andFillColor:[UIColor blueColor]];

}

QuartzView

- (void)drawRectCGRect)rect
{
    self.context = UIGraphicsGetCurrentContext();
    UIColor *color = [UIColor colorWithRed:0 green:1 blue:0 alpha:0.5];

    // this code draws a square as expected
    float w = self.frame.size.width / 2;
    float h = self.frame.size.height / 2;
    color = [UIColor blueColor];
    CGPoint center = CGPointMake(w, h);
    [self drawRectWithCenter:center andWidth:20 andHeight:20 andFillColor:color];
}

- (void)drawRectWithCenterCGPoint)center andWidthfloat)w andHeightfloat)h andFillColorUIColor *)color
{
    CGContextSetFillColorWithColor(self.context, color.CGColor);
    CGContextSetRGBStrokeColor(self.context, 0.0, 1.0, 0.0, 1);

    CGRect rectangle = CGRectMake(center.x - w / 2, center.x - w / 2, w, h);

    CGContextFillRect(self.context, rectangle);
    CGContextStrokeRect(self.context, rectangle);
}

注意

编辑

我注意到从左下角开始绘制父级时正方形的 x/y 值是 0,0,而通常 0,0 是左上角。



Best Answer-推荐答案


UIGraphicsGetCurrentContext() 的返回值仅在 drawRect 方法内有效。您不能也不得在任何其他方法中使用该上下文。所以 self.context 属性应该只是一个局部变量。

drawRectWithCenter 方法中,您应该将所有参数存储在属性中,然后使用 [self setNeedsDisplay] 请求 View 更新。这样,框架将使用新信息调用 drawRectdrawRectWithCenter 方法应该是这样的

- (void)drawRectWithCenterCGPoint)center andWidthfloat)w andHeightfloat)h andFillColorUIColor *)color
{
    self.showCenter = center;
    self.showWidth = w;
    self.showHeight = h;
    self.showFillColor = color;
    [self setNeedsDisplay];
}

当然,drawRect 函数需要获取该信息,并进行适当的绘图。

关于iOS - 父/ subview 的 Quartz 绘图问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37353312/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4