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

时间:2009-07-01 21:14:08

标签: iphone objective-c cocoa-touch

如何在联系信息或Facebook应用中创建“人物照片”按钮? (具有小半径的灰色和圆形边框以及在其内部裁剪的图像)

编辑:

它必须显然适用于所有照片,而不仅仅是我在Photoshop中预渲染的照片。

我想我可以使用蒙版等手动完成,但Facebook应用程序完全就像联系人应用程序一样,所以我怀疑在SDK中有一些方法可以做到这一点。

2 个答案:

答案 0 :(得分:2)

在这里你(我:P)去:

+ (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 alpha,但由于抗锯齿为2个像素中的每一个提供了一些alpha,我将其设置为1并且它恰好出现在右边。如果我禁用抗锯齿,那么角落不会全部舍入:/

答案 1 :(得分:1)

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

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