IOS开发基础知识--碎片30

1:ios 相册操作 ALAssetsLibrary 知识点

a ALAssetsLibrary 实例为我们提供了获取相册(照片app)中的图片和视频的功能。在ios8 photos framework代替了ALAssetsLibrary。

在使用ALAssetsLibrary时,我们需要申明它的实例。

ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];

 

b. 迭代获取相册ALAssetsGroup:

- (void)enumerateGroupsWithTypes:(ALAssetsGroupType)types
                      usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock
                    failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock

ALASSetsGroupType类型:

ALAssetsGroupLibrary:从iTunes 来的相册内容(如本身自带的向日葵照片)。

ALAssetsGroupAlbum:设备自身产生或从iTunes同步来的照片,但是不包括照片流跟分享流中的照片。(例如从各个软件中保存下来的图片)

ALAssetsGroupEvent 相机接口事件产生的相册

ALAssetsGroupFaces 脸部相册(具体不清楚)

ALAssetsGroupSavedPhotos 相机胶卷照片

ALAssetsGroupPhotoStream 照片流

ALAssetsGroupAll 除了ALAssetsGroupLibrary上面所的内容。


例如:ALAssetsLibraryGroupsEnumerationResultsBlock

  ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
    ALAssetsFilter *onlyPhotosFilter = [ALAssetsFilter allPhotos];
        [group setAssetsFilter:onlyPhotosFilter];
        if ([group numberOfAssets] > 0)
        {
            [self.imageGroup addObject:group];
        }
        else
        {
            [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
        }
    };

上面就是迭代AlAssetsGroup的block。每迭代一次就把相应的AlAssetsGroup保存在一个可变的数组之中。AlAssetsGroup中的一些属性表明了这个相册的特征。比如: 
posterImage 相册的缩略图

numberOfAssets 相册中照片的数量

 

c:Asset 属性

– valueForProperty:
1.ALAssetPropertyType 资源的类型(照片,视频)
2.ALAssetPropertyLocation 资源地理位置(无位置信息返回null)
3.ALAssetPropertyDuation 播放时长(照片返回ALErorInvalidProperty)
4.ALAssetPropertyOrientation 方向(共有8个方向,参见:ALAssetOrientation)
5.ALAssetPropertyDate 拍摄时间(包含了年与日时分秒)
6.ALAssetPropertyRepresentations 描述(打印看了下,只有带后缀的名称)
7.ALAssetPropertyURLs(返回一个字典,键值分别是文件名和文件的url)
8.ALAssetPropertyAssetURL 文件的url )
editable property(指示资源是否可以编辑,只读属性)
originalAsset property(原始资源。若没有保存修改后资源,则原始资源为nil)

    for (ALAsset *asset in assets) {
       NSURL *assetURL= [asset valueForProperty:ALAssetPropertyAssetURL];
    }

Accessing Representations
– defaultRepresentation
– representationForUTI:
– thumbnail(小正方形的缩略图)
– aspectRatioThumbnail(按原始资源长宽比例的缩略图)

另外一个小实例:

                        UIImage* ni = [UIImage imageNamed:@"new.png"];
                        //修改指定路径的图片资源内容,替换掉原来的内容
                        [asset setImageData:UIImageJPEGRepresentation(ni, 1.0) metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
                            NSLog(@"new:%@",assetURL);
                        }];
                        //根据给定的图片内容,重新生成一张新图
                        [asset writeModifiedImageDataToSavedPhotosAlbum:UIImageJPEGRepresentation(ni, 1.0) metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
                            NSLog(@"new:%@",assetURL);
                        }];
                        //获取资源图片的详细资源信息
                        ALAssetRepresentation* representation = [asset defaultRepresentation];
                        //获取资源图片的长宽
                        CGSize dimension = [representation dimensions];
                        //获取资源图片的高清图
                        [representation fullResolutionImage];
                        //获取资源图片的全屏图
                        [representation fullScreenImage];
                        //获取资源图片的名字
                        NSString* filename = [representation filename];
                        NSLog(@"filename:%@",filename);
                        //缩放倍数
                        [representation scale];
                        //图片资源容量大小
                        [representation size];
                        //图片资源原数据
                        [representation metadata];
                        //旋转方向
                        [representation orientation];
                        //资源图片url地址,该地址和ALAsset通过ALAssetPropertyAssetURL获取的url地址是一样的
                        NSURL* url = [representation url];
                        NSLog(@"url:%@",url);
                        //资源图片uti,唯一标示符
                        NSLog(@"uti:%@",[representation UTI]);

 

2:Attribute运用(几段代码)

其中addAttribute可以增加不同的属性,有些属性值是要在NSMutableParagraphStyle里面进行设置例如下面第一段代码中NSParagraphStyleAttributeName,有些可以直接设置值如NSForegroundColorAttributeName

            NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
            [style setLineSpacing:5];
            [muttext addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, muttext.length)];
            [muttext addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, muttext.length)];
            _myLabel.attributedText = muttext;
NSMutableParagraphStyle *paragraph=[[NSMutableParagraphStyle alloc]init];  
 paragraph.alignment=NSTextAlignmentCenter;//居中  

NSDictionary* attrs =@{NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:30],//文本的颜色 字体 大小  
                           NSForegroundColorAttributeName:[UIColor redColor],//文字颜色  
                           NSParagraphStyleAttributeName:paragraph,//段落格式  
//                           NSBackgroundColorAttributeName:[UIColor blueColor],//背景色  
                           NSStrokeWidthAttributeName:@3, //描边宽度  
                           NSStrokeColorAttributeName:[UIColor greenColor],//设置 描边颜色,和NSStrokeWidthAttributeName配合使用,设置了这个NSForegroundColorAttributeName就失效了  
                          
//                           NSStrikethroughStyleAttributeName:@1,//删除线,数字代表线条宽度  
                           NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),//下划线,值为一个枚举类型,大家可以分别试试  
                           };  
-(NSMutableAttributedString*)setTitle
{
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"准备量房"];
    [title addAttribute:NSForegroundColorAttributeName value:COLOR_NAV_TITLE range:NSMakeRange(0, title.length)];
    [title addAttribute:NSFontAttributeName value:SYSTEMFONT(18) range:NSMakeRange(0, title.length)];
    return title;
}
1.如果只是静态显示textView的内容为设置的行间距,执行如下代码:

//    textview 改变字体的行间距 
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; 
    paragraphStyle.lineSpacing = 10;// 字体的行间距 
     
    NSDictionary *attributes = @{ 
                                 NSFontAttributeName:[UIFont systemFontOfSize:15], 
                                 NSParagraphStyleAttributeName:paragraphStyle 
                                 }; 
    textView.attributedText = [[NSAttributedString alloc] initWithString:@"输入你的内容" attributes:attributes];

 

2.如果是想在输入内容的时候就按照设置的行间距进行动态改变,那就需要将上面代码放到textView的delegate方法里

-(void)textViewDidChange:(UITextView *)textView

{

    //    textview 改变字体的行间距

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];

    paragraphStyle.lineSpacing = 20;// 字体的行间距

    

    NSDictionary *attributes = @{

                                 NSFontAttributeName:[UIFont systemFontOfSize:15],

                                 NSParagraphStyleAttributeName:paragraphStyle

                                 };

    textView.attributedText = [[NSAttributedString alloc] initWithString:textView.text attributes:attributes];

 

}

 

3:中文输入法的键盘上有联想、推荐的功能,所以可能导致文本内容长度上有些不符合预期,导致越界

*** Terminating app due to uncaught exception 'NSRangeException', reason: 'NSMutableRLEArray replaceObjectsInRange:withObject:length:: Out of bounds'

处理方式如下(textView.markedTextRange == nil

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (textView.text.length >= self.textLengthLimit && text.length > range.length) {
        return NO;
    }
    
    return YES;
}

- (void)textViewDidChange:(UITextView *)textView
{
    self.placeholder.hidden = (self.textView.text.length > 0);
    
    if (textView.markedTextRange == nil && self.textLengthLimit > 0 && self.text.length > self.textLengthLimit) {
        textView.text = [textView.text substringToIndex:self.textLengthLimit];
    }
}

 4:UITableView滚动值获取

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    UIColor *color = [UIColor blueColor];
    CGFloat offsetY = scrollView.contentOffset.y;
    if (offsetY > 0) {
        CGFloat alpha = 1 - ((64 - offsetY) / 64);
        self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:alpha];
    } else {
         self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:0];
    }
}

5:YYCache缓存的运用

#import <YYCache/YYCache.h>
#import "UserInfo.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    NSString *path = NSHomeDirectory();//主目录
    NSLog(@"NSHomeDirectory:%@",path);
    
    
    YYCache *cache = [[YYCache alloc]initWithName:@"cacheTest"];
    id getCache = [cache objectForKey:@"cache"];
    if (getCache) {
        NSLog(@"getObject:%@",getCache);
    }
    else
    {
        [cache setObject:@"test" forKey:@"cache"];
        NSLog(@"setObject:%@",getCache);
    }
    
    
    id  getDicCache = [cache objectForKey:@"userDic"];
    if (getDicCache) {
        NSDictionary *dic = (NSDictionary *)[cache objectForKey:@"userDic"];
        NSLog(@"getDicObject:%@", dic);
        NSLog(@"getDicObject:%@", [dic objectForKey:@"name"]);
    }
    else
    {
        NSDictionary *dic = @{@"name":@"alex",@"age":@18};
        [cache setObject:dic forKey:@"userDic"];
        NSLog(@"setDicObject:%@",dic);
    }
    
    
    NSString *basePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) firstObject];
    basePath = [basePath stringByAppendingPathComponent:@"FileCacheBenchmarkLarge"];
    
    YYKVStorage *yykvFile = [[YYKVStorage alloc] initWithPath:[basePath stringByAppendingPathComponent:@"yykvFile"] type:YYKVStorageTypeFile];
    YYKVStorage *yykvSQLite = [[YYKVStorage alloc] initWithPath:[basePath stringByAppendingPathComponent:@"yykvSQLite"] type:YYKVStorageTypeSQLite];
    YYDiskCache *yy = [[YYDiskCache alloc] initWithPath:[basePath stringByAppendingPathComponent:@"yy"]];
    yy.customArchiveBlock = ^(id object) {return object;};
    yy.customUnarchiveBlock = ^(NSData *object) {return object;};
    
    int count = 1000;
    NSMutableArray *keys = [NSMutableArray new];
    NSMutableArray *values = [NSMutableArray new];
    for (int i = 0; i < count; i++) {
        NSString *key = @(i).description;
        NSNumber *value = @(i);
        [keys addObject:key];
        [values addObject:value];
    }
    
    //写入文件
    for (int i = 44; i < count; i++) {
        [yykvFile saveItemWithKey:keys[i] value:[@"wujy" dataUsingEncoding:NSUTF8StringEncoding]
                         filename:keys[i] extendedData:nil];
    }
    
    //读取
    YYKVStorageItem *item = [yykvFile getItemForKey:keys[200]];
    NSString *aString = [[NSString alloc] initWithData:item.value encoding:NSUTF8StringEncoding];
    NSLog(@"%@",aString);
    
    //写入数据库
    for (int i = 0; i < count; i++) {
        [yykvSQLite saveItemWithKey:keys[i] value:[@"cnblogs" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    
    YYKVStorageItem *sqlitem = [yykvFile getItemForKey:keys[200]];
    NSString *asqlString = [[NSString alloc] initWithData:sqlitem.value encoding:NSUTF8StringEncoding];
    NSLog(@"%@",asqlString);
}

 

你可能感兴趣的:(IOS开发基础知识--碎片30)