iOS 切割圆角图片、图片文件格式判断

 

1.切割圆角图片

 

    // 性能不好,适合圆角图形数量比较少的情况
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
   //设置圆角
    imageView.layer.cornerRadius = imageView.frame.size.width / 2;
   //将多余的部分切掉
    imageView.layer.masksToBounds = YES;

 

 

 

// 设置圆形图片(放到分类中使用) 
- (UIImage *)circularImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 设置圆形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

 

 

 

// 圆角图片
- (UIImage *)cornerRoundedImage {
    
    //进行画图
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [UIScreen mainScreen].scale);
    //使用贝塞尔曲线画出一个圆角图,圆角半径为12
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    [[UIBezierPath bezierPathWithRoundedRect:rect
                                cornerRadius:12] addClip];
    [self drawInRect:rect];
    
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    //结束画图
    UIGraphicsEndImageContext();
    return image;
    
}

 

 

 

 

2.图片文件格式判断

 

//通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";     
        case 0x47:
            return @"gif";        
        case 0x49:   
        case 0x4D:
            return @"tiff";        
        case 0x52:  
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}


NSString *path = @"http://xxx.xxx.xxx/xxx.png";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
//调用
NSString *string = [self contentTypeForImageData:data];
//输出结果为 png
NSLog(@"%@",string);

 

posted @ 2016-08-20 10:32  Ficow  阅读(548)  评论(0编辑  收藏  举报