IOS开发-设置头像(圆形)

app 头像设置,做成圆形的越来越多。而实现并不是很难,但是图像处理好很重要。

<span style="font-size:14px;">UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(200,100 , 100, 100)];
    UIImage *image = [UIImage imageNamed:@"1"];
    imgV.image = image;
    [imgV.layer setCornerRadius:CGRectGetHeight([imgV bounds])/2];
    imgV.layer.masksToBounds = YES;
    [self.view addSubview: imgV];</span>

上面的代码是将 长宽都是100的imageView 以50为半径 切的一个圆。

另外一个是等比例拉伸的。功能实现是,从本地或者相册选择图片来做头像并作保存。

#import "ViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
@interface ViewController ()

@property(nonatomic, strong) UIImageView *img;
@property(nonatomic, strong) NSData *fileData;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.img = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];
    self.img.image = selfPhoto;
    [self.img.layer setCornerRadius:CGRectGetHeight([self.img bounds]) / 2];
    self.img.layer.masksToBounds = YES;
    [self.view addSubview:_img];

    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(100, 300, 100, 50)];
    [self.view addSubview:btn];
    [btn setTitle:@"换图" forState:UIControlStateNormal];
//    [btn addTarget:self action:@selector(takePictureClick) forControlEvents:UIControlEventTouchUpInside];
    btn.backgroundColor = [UIColor lightGrayColor];

    UIImageView *imgV = [[UIImageView alloc]initWithFrame:CGRectMake(200,100 , 100, 100)];
    UIImage *image = [UIImage imageNamed:@"1"];
    imgV.image = image;
    [imgV.layer setCornerRadius:CGRectGetHeight([imgV bounds])/2];
    imgV.layer.masksToBounds = YES;
    [self.view addSubview: imgV];

}

//从相册获取图片
-(void)takePictureClick
{
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"相机",@"本地相簿",nil];
    [actionSheet showInView:self.view];

}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0://照相机
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;

        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    else if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeMovie]) {
        NSString *videoPath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
        self.fileData = [NSData dataWithContentsOfFile:videoPath];
    }
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

//保存头像
- (void)saveImage:(UIImage *)image {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    NSLog(@"imageFile->>%@",imageFilePath);
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(100, 100)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];
    //写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    self.img.image = selfPhoto;
}

//保持原来的长宽比,生成一个缩略图
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

版权声明:本文为博主原创文章,未经博主允许不得转载。

时间: 2024-10-16 20:30:01

IOS开发-设置头像(圆形)的相关文章

ios 开发选取头像,图片库,相机,裁取图片

需要遵守的代理协议:UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate @property (nonatomic, strong) UIActionSheet *avatarActionSheet; 第一步:点击头像cell需要做的事情 [self.avatarActionSheet showInView:self.view]; 第二步: #pragma mark - 点击头像

iOS UIImageView设置为圆形

UIImageView设置为圆形的方法: _Image.layer.masksToBounds = YES; _Image.layer.cornerRadius = self.Image.frame.size.width / 2; 设置加载本地图片的方法: _Image.image = [UIImage imageNamed:@"Image"];//图片“Image”为xcassets里的set名称

iOS之设置头像(访问系统相册、本地上传)

1. UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:                               @"设置头像" delegate:self cancelButtonTitle:@"取消"                       destructiveButtonTitle:nil otherButtonTitles:@"选择本地图片",@&

iOS开发-设置在使用NavigateController时View的顶部位置

  最近我在开发中遇到了一个问题,在使用NavigationController时内部的ViewController的View总是与屏幕顶部对齐,而我们有时候不需要这种效果: 在开发过程中,我们可能会需要这种布局: 需要加这句话,意思是让View的所有边都紧贴在容器内部. 即可   Ref: https://developer.apple.com/library/ios/documentation/WindowsViews/Conceptual/ViewControllerCatalog/Cha

iOS开发学习-给圆形图片添加边框

imageView.layer.cornerRadius = imageView.bounds.size.width * 0.5;// 设置圆角刚好是自身宽度的一半,就刚好是圆形 imageView.layer.masksToBounds = YES; imageView.layer.borderWidth = 1; //边框宽度 imageView.layer.borderColor = [[UIColor grayColor] CGColor];//边框颜色

iOS开发设置tableview的分割线

在开发ios8中大家会发现系统自带的分割线前面会有15个像素的空余,那么怎么才能像以前一样的,我看到别人的博客有提到 首先在viewdidload中设置好你的系统分割线,然后加上如下代码 listView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.contentView.frame.size.width,self.contentView.frame.size.height) style:UITableViewStylePla

iOS开发--设置UIButton

1.设置title 1 [btn setTitle: @"search" forState: UIControlStateNormal]; 2.设置字体 1 //[btn setFont: [UIFont systemFontSize: 14.0]]; //这种可以用来设置字体的大小,但是可能会被移除 2 //应该使用 3 btn.titleLabel.font = [UIFont systemFontOfSize: 14.0]; 3.Title对齐 有些时候我们想让UIButton的

ios开发-设置view背景

1. 直接给View设置背景 self.view.backgroundColor = [UIColor colorWithPatternImage: [UIImage imageNamed:@"1.jpg"] ]; 2.给UIScrollView 设置背景图片 这个一般在图片较大,并且视图需要滚动时候使用. 原理都一样,调个函数就是了. // 初始化滚动试图 UIScrollView *tempScrollView = (UIScrollView*)self.view; // 设置背景

iOS开发-- 设置UIButton的文字显示位置、字体的大小、字体的颜色

btn.frame = CGRectMake(x, y, width, height); [btn setTitle: @"search" forState: UIControlStateNormal]; //设置按钮上的自体的大小 //[btn setFont: [UIFont systemFontSize: 14.0]];    //这种可以用来设置字体的大小,但是可能会在将来的SDK版本中去除改方法 //应该使用 btn.titleLabel.font = [UIFont sys

ios开发设置button的选中状态图片

可以在故事版中设置好所需要的图片,然后现在h文件中声明按钮的属性和方法 - (IBAction)moodViewShow:(id)sender; @property (weak, nonatomic) IBOutlet UIButton *faceBtn; 并且与故事版完成连接,然后在按钮的方法里设置选中的状态 - (IBAction)moodViewShow:(id)sender { if ([self.faceBtn isSelected]) {//如果是选中状态就置为no, [self.f