2009-07-01 7 views
3

Comment puis-je créer un bouton "photo de personne" comme celui dans les informations de contact ou dans l'application Facebook? (Bordure grise et arrondie avec un petit rayon et une image qui est recadrée à l'intérieur)Bouton photo comme dans les contacts et l'application Facebook

Edit:

Il doit évidemment travailler pour toutes les photos, pas seulement un que je prerender dans Photoshop. Je suppose que je pourrais le faire manuellement en utilisant des masques, etc, mais l'application Facebook le fait exactement comme l'application de contacts, donc je soupçonne qu'il ya un moyen de le faire dans le SDK.

Répondre

2

Ici vous (I: P) aller:

+ (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; 
} 

Basé en grande partie au this question.

Un problème est que la bordure est en réalité 2px de large (bien que 1px tombe en dehors de la zone de clip) en raison de l'anti-aliasing. Idéalement, la bordure aurait ~ 0.5 alpha, mais comme l'antialiasing donne à chacun des 2 pixels de l'alpha, je l'ai mis à 1 et il sort à peu près juste. Si je désactive l'antialiasing, alors les coins ne sont pas tous arrondis:/

1

Créer comme une image (comme "person.png"), puis le charger comme ceci:

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