iOS—UIImageView繪製圓形圖片

參考網上的資料,自實現了一個UIImageView繪製圓形圖片功能。

先看效果:


代碼如下:

- (void)buttonAction:(id)sender {

    //方式1,見上圖的方式1效果。通過imageviewlayer來操作

    UIImageView *imageView1 = [[UIImageViewallocinitWithImage:[UIImageimageNamed:@"11.png"]];

    imageView1.frame = CGRectMake(60,100100100);

    imageView1.layer.masksToBounds =YES;

    imageView1.layer.cornerRadius =50;

    [self.view addSubview:imageView1];

    

    //方式2,見上圖的方式2效果。對畫布裁剪成圓形,然後再將原始圖像畫出來

    UIImageView *imageView2 = [[UIImageViewallocinitWithFrame:CGRectMake(60,250,100,100)];

    UIImage *image2 = [UIImageimageNamed:@"12.png"];

    imageView2.image = [selfcircleImage:image2 withParam:0];

    [self.view addSubview:imageView2];

}


-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {

    UIGraphicsBeginImageContext(image.size);

    CGContextRef context =UIGraphicsGetCurrentContext();

    //圓的邊框寬度爲2,顏色爲紅色

    CGContextSetLineWidth(context,2);

    CGContextSetStrokeColorWithColor(context, [UIColorredColor].CGColor);

    CGRect rect = CGRectMake(inset, inset, image.size.width - inset *2.0f, image.size.height - inset *2.0f);

    CGContextAddEllipseInRect(context, rect);

    CGContextClip(context);

    //在圓區域內畫出image原圖

    [image drawInRect:rect];

    CGContextAddEllipseInRect(context, rect);

    CGContextStrokePath(context);

    //生成新的image

    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newimg;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章