图片中心对齐三合一

2017-11-09  本文已影响10人  child_cool

如果下面的描述和方法不太清晰,请在这里下载
图片合并的主要内容

+ (UIImage *)getCenterImage:(UIImage *)image {
    UIImage *top_img = [UIImage imageNamed:@"播放"];
    CGImageRef top_imgRef = top_img.CGImage;
    CGFloat top_w = CGImageGetWidth(top_imgRef);
    CGFloat top_h = CGImageGetHeight(top_imgRef);
    
    
    UIImage *center_img = [UIImage yj_resizeImage:image.yj_circleImage withNewSize:CGSizeMake(138, 138)];
    if (image == nil) {
        center_img = [UIImage imageNamed:@"中间圆"];
    }
    
    CGImageRef center_imgRef = center_img.CGImage;
    CGFloat center_w = CGImageGetWidth(center_imgRef);
    CGFloat center_h = CGImageGetHeight(center_imgRef);
    
    //以1.png的图大小为底图
    UIImage *bottom_img = [UIImage imageNamed:@"底"];
    CGImageRef bottom_imgRef = bottom_img.CGImage;
    CGFloat bottom_w = CGImageGetWidth(bottom_imgRef);
    CGFloat bottom_h = CGImageGetHeight(bottom_imgRef);

    //以1.png的图大小为画布创建上下文
    UIGraphicsBeginImageContext(CGSizeMake(bottom_w, bottom_h));
    
    [bottom_img drawInRect:CGRectMake(0, 0, bottom_w, bottom_h)];//先把1.png 画到上下文中
    [center_img drawInRect:CGRectMake((bottom_w-center_w)/2, (bottom_h-center_h)/2 + 7, center_w, center_h)];//再把小图放在上下文中
    [top_img drawInRect:CGRectMake((bottom_w-top_w)/2, (bottom_h-top_h)/2 + 7, top_w, top_h)];//再把小图放在上下文中
    // 注意:这里不能打开否则会出现野指针,导致崩溃,即使把图片保存至沙盒然后在注销一样会出现问题
//    CGImageRelease(top_imgRef);
//    CGImageRelease(center_imgRef);
//    CGImageRelease(bottom_imgRef);
    UIImage *resultImg = UIGraphicsGetImageFromCurrentImageContext();//从当前上下文中获得最终图片
    UIGraphicsEndImageContext();//关闭上下文
    
    return [UIImage yj_resizeImage:resultImg withNewSize:CGSizeMake(60, 60)];
}
/**
 图片剪切成圆形
 
 @return 圆形图片
 */
- (UIImage *)yj_circleImage {
    // NO透明
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获得上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    // 添加一个圆
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctx, rect);
    // 裁剪
    CGContextClip(ctx);
    // 将图片画上去
    [self drawInRect:rect];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    //结束上下文
    UIGraphicsEndImageContext();
    return image;
}
/**
 *  获得指定size的图片
 *
 *  @param image   原始图片
 *  @param newSize 指定的size
 *
 *  @return 调整后的图片
 */
+ (UIImage *)yj_resizeImage:(UIImage *) image withNewSize:(CGSize) newSize{
    
    UIGraphicsBeginImageContext(newSize);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}
上一篇下一篇

猜你喜欢

热点阅读