代码之家  ›  专栏  ›  技术社区  ›  Laurent Crivello

通过CGContext绘制uibutton图像

  •  0
  • Laurent Crivello  · 技术社区  · 6 年前

    为了在按钮上显示进度圆,我在 CGContext ,然后传给 UIImage 最后到了 UIButton 图像。然而,它所画的是一个填充的正方形:

    CGRect rect = CGRectMake(0, 0, myButton.frame.size.width, myButton.frame.size.height);
    
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, 1);
    [[UIColor colorWithRed:1.0 green:0. blue:0. alpha:1.0] setStroke];
    [[UIColor colorWithWhite:0.9 alpha:1.0] setFill];
    CGContextMoveToPoint(ctx, rect.size.width/2., rect.size.height/2.);
    CGContextAddArc(ctx,
                    rect.size.width/2., // centerX
                    rect.size.height/2.,  // centerY
                    rect.size.width, // radius
                    0, // start Angle
                    M_PI/2., // end Angle
                    1); // clockwise
    CGContextDrawPath(ctx,kCGPathFillStroke);
    
    UIImage *progressImg=UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [myButton setImage:progressImg forState:UIControlStateNormal];
    

    为什么我得到一个填充的正方形而不是一个填充的部分弧?这是把进度条画成圆的最好方法吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   matt    6 年前

    你的弧半径不对。实际的弧绘制在上下文边界之外。更改

    CGContextAddArc(ctx,
                    rect.size.width/2., // centerX
                    rect.size.height/2.,  // centerY
                    rect.size.width, // radius
                    0, // start Angle
                    M_PI/2., // end Angle
                    1); // clockwise
    

    CGContextAddArc(ctx,
                    rect.size.width/2., // centerX
                    rect.size.height/2.,  // centerY
                    rect.size.width/2., // radius
                    0, // start Angle
                    M_PI/2., // end Angle
                    1); // clockwise
    

    另外,请注意,根据您的按钮类型,您可能最终会得到被视为 模板 而不是你画的实际图像。要解决这个问题,您可以说(在使用按钮中的图像之前):

    progressImg = 
        [progressImg imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];