电竞比分网-中国电竞赛事及体育赛事平台

分享

iOS小知識點05

 宇智波瞬潤 2016-05-10

UIImageView添加圓角

在項目中提供的圖片是矩形的,現(xiàn)要改成圓角圖片,于是找了一些資料,下面是添加圓角圖片的方法
創(chuàng)建UIImage的分類UIImage+ImageRounderCorner
UIImage+ImageRounderCorner.h文件中

#import <UIKit/UIKit.h>

@interface UIImage (ImageRounderCorner)

/** 調(diào)用此方法,返回一個帶有圓角的UIImage對象
 *  參數(shù)一:圓角半徑
 *  參數(shù)二:圖片的大小
 */
- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size;

@end

UIImage+ImageRounderCorner.m文件中

#import "UIImage+ImageRounderCorner.h"

@implementation UIImage (ImageRounderCorner)

- (UIImage *)imageAddCornerWithRadius:(CGFloat)radius andSize:(CGSize)size {

    CGRect rect = CGRectMake(0, 0, size.width, size.height);
// 創(chuàng)建一個基于位圖的上下文(context),并將其設置為當前上下文,size為新創(chuàng)建的位圖上下文大小
    // opaque 透明開關 // scale 縮放因子
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    // 拿到當前上下文對象
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 創(chuàng)建貝塞爾曲線
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    // 添加路徑
    CGContextAddPath(ctx, path.CGPath);
    // 裁剪
    CGContextClip(ctx);
    // 繪圖
    [self drawInRect:rect];
    // 填充繪制
    CGContextDrawPath(ctx, kCGPathFillStroke);
    // 從當前位圖上下文的內(nèi)容輸出一個UIImage圖片
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // 上下文棧pop出創(chuàng)建的context
    UIGraphicsEndImageContext();

    return newImage;
}

@end

使用:
在控制器中導入 #import "UIImage+ImageRounderCorner.h"

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImage *image = [UIImage imageNamed:@"image"];
    UIImage *cornerImage = [image imageAddCornerWithRadius: 50.0 andSize:CGSizeMake(50.0, 50.0)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
    [self.view addSubview:imageView];
}

運行后,發(fā)現(xiàn),將原有的矩形圖片轉換為了帶圓角的圖片。

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多