【问题标题】:iOS graphics appearing from upper left corner on custom controliOS 图形从自定义控件的左上角出现
【发布时间】:2015-04-20 22:38:25
【问题描述】:

我一直在做一个圆形控件,我做得很好,除了第一次渲染时图形从左上角出现。

整个控件是UIControl 的子类,自定义CALayer 会渲染一个圆圈。

这是渲染圆圈的代码:

- (void) drawInContext:(CGContextRef)ctx{
id modelLayer = [self modelLayer];
CGFloat radius = [[modelLayer valueForKey:DXCircularControlLayerPropertyNameRadius] floatValue];
CGFloat lineWidth = [[modelLayer valueForKey:DXCircularControlLayerPropertyNameLineWidth] floatValue];
//NSLog(@"%s, angle: %6.2f, radius: %6.2f, angle_m: %6.2f, radius_m: %6.2f", __func__, self.circleAngle, self.circleRadius, [[modelLayer valueForKey:@"circleAngle"] floatValue], [[modelLayer valueForKey:@"circleRadius"] floatValue]);

// draw circle arc up to target angle

CGRect frame = self.frame;
CGContextRef context = ctx;

CGContextSetShouldAntialias(context, YES);
CGContextSetAllowsAntialiasing(context, YES);

// draw thin circle

//CGContextSetLineWidth(context, <#CGFloat width#>)

// draw selection circle

CGContextSetLineWidth(context, lineWidth);
CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
CGContextAddArc(context, frame.size.width / 2.0f, frame.size.height / 2.0f, radius, 0.0f, self.circleAngle, 0);

CGContextStrokePath(context);

CGContextSetShouldAntialias(context, NO);
}

这是一个问题的video

如果你仔细观察,你会发现圆的渲染不知何故没有居中。它从左上角倾斜。 这只发生在第一次做动画时。

我知道如果一个错误开始和结束动画提交块时会发生这种情况,但我在这里不使用它们。

以防万一这里是此控件的 bitbucket repo 的链接:

【问题讨论】:

    标签: ios objective-c core-graphics core-animation


    【解决方案1】:

    绘制方法没有问题 - 你在设置图层的框架时有点搞砸了;-)

    您正在- (void) setAngle:(CGFloat)angle 方法中设置圆形控制层的框架。这意味着当您为角度属性设置动画时第一次设置框架 - 因此框架也将被设置动画。在- (void) commonInitDXCircularControlView 方法中设置框架。

    如果您要创建自定义层,请查看[UIView layerClass] 方法。使用它可以让您免于边界/框架管理的麻烦。

    【讨论】:

    • 为了让它工作,我把它放在layoutSubviews 方法中。也许是因为自动布局.. 谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多