代码之家  ›  专栏  ›  技术社区  ›  Jaka Jančar

照片按钮,如联系人和Facebook应用程序中的按钮

  •  3
  • Jaka Jančar  · 技术社区  · 17 年前

    如何创建联系人信息或Facebook应用程序中的“人物照片”按钮?(灰色圆形边框,半径较小,内部裁剪图像)

    就像联系人应用程序一样,所以我怀疑在SDK中有一些方法可以做到这一点。

    2 回复  |  直到 17 年前
        1
  •  2
  •   Community Mohan Dere    9 年前

    + (UIImage *)imageWithBorderForImage:(UIImage *)image
    {
        CGFloat radius = 5;
        CGSize size = image.size;
    
        radius = MIN(radius, .5 * MIN(size.width, size.height));
        CGRect interiorRect = CGRectInset(CGRectMake(0, 0, size.width, size.height), radius, radius);
    
        UIGraphicsBeginImageContext(size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSaveGState(context);
    
        CGMutablePathRef borderPath = CGPathCreateMutable();
        CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMinY(interiorRect), radius, 1.0*M_PI, 1.5*M_PI, NO);
        CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMinY(interiorRect), radius, 1.5*M_PI, 0.0*M_PI, NO);
        CGPathAddArc(borderPath, NULL, CGRectGetMaxX(interiorRect), CGRectGetMaxY(interiorRect), radius, 0.0*M_PI, 0.5*M_PI, NO);
        CGPathAddArc(borderPath, NULL, CGRectGetMinX(interiorRect), CGRectGetMaxY(interiorRect), radius, 0.5*M_PI, 1.0*M_PI, NO);
    
        CGContextBeginPath(context);
        CGContextAddPath(context, borderPath);
        CGContextClosePath(context);
        CGContextClip(context);
    
        [image drawAtPoint:CGPointMake(0,0)];
    
        CGContextBeginPath(context);
        CGContextAddPath(context, borderPath);
        CGContextClosePath(context);
    
        CGContextSetRGBStrokeColor(context, 0.5, 0.5, 0.5, 1.0);
        CGContextSetLineWidth(context, 1.0);
        CGContextStrokePath(context);
    
        CGPathRelease(borderPath);
    
        UIImage *borderedImage = UIGraphicsGetImageFromCurrentImageContext();
        CGContextRestoreGState(context);
        UIGraphicsEndImageContext();
    
        return borderedImage;
    }
    

    this question .

    一个问题是,由于抗锯齿,边界实际上是2px宽(尽管1px落在剪辑区域之外)。理想情况下,边框的阿尔法值约为0.5,但由于抗锯齿技术为2个像素中的每一个像素都提供了一些阿尔法值,我将其设置为1,结果大致正确。如果我禁用抗锯齿,那么角就不会完全变圆:/

        2
  •  1
  •   Dave DeLong    17 年前

    将其创建为图像(如“person.png”),然后按如下方式加载:

    UIImage *personImage = [UIImage imageNamed:@"person.png"];
    [[myButton imageView] setImage:personImage];
    //where myButton is a UIButton of type UIButtonTypeCustom