分享

IOS 图片裁剪 ? IT

 求知665 2015-08-02
Objective-C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/////////////////////
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(50, 100, 200, 350)];
    UIImage *img = [UIImage imageNamed:@"test.jpg"];
    imageview.image = [self getThumbnailImgFromImage:img];
    [self.view addSubview:imageview];
    [imageview release];
    
}
- (UIImage *)getThumbnailImgFromImage:(UIImage *)image
{
    CGSize origImageSize = [image size];
    NSLog(@"origImageSize,width=%f",image.size.width);
    NSLog(@"origImageSize,height=%f",image.size.height);
    
    CGRect newRect;
    newRect.origin = CGPointZero;
    newRect.size = CGSizeMake(200, 350);
    
    ///缩放比
    float ratio = MAX(newRect.size.width/origImageSize.width,
                      newRect.size.height/origImageSize.height);
    
    ///创建位图上下文
    UIGraphicsBeginImageContext(newRect.size);
    
    ///切个圆角
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:10];
    
    [path addClip];
    
    ///新图片的frame ////如果不计算比例,得到的图片是原始图片的裁剪版,不是缩小版。
    CGRect thumbnailImag;
    thumbnailImag.size.width = ratio * origImageSize.width;
    thumbnailImag.size.height = ratio * origImageSize.height;
    thumbnailImag.origin.x = (newRect.size.width - thumbnailImag.size.width) / 2.0;
    thumbnailImag.origin.y = (newRect.size.height - thumbnailImag.size.height) / 2.0;
    
    ///绘图
    [image drawInRect:thumbnailImag];
    
    ///获取图片
    UIImage * small = UIGraphicsGetImageFromCurrentImageContext();
    NSLog(@"small,width=%f",small.size.width);
    NSLog(@"small,height=%f",small.size.height);
    /**
     *得到的图片是按比例缩小的,如果不按比例缩小,那么直接给一个CGRect,
     *他会直接裁剪。可能w h 小裁剪的就是原始图片的部分;
     */
    
    ///data
    //NSData *data = UIImagePNGRepresentation(small);
    
    //回收内存
    UIGraphicsEndImageContext();
    
    return small;
    
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约