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] > )
{
[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:];
[muttext addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(, muttext.length)];
[muttext addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(, muttext.length)];
_myLabel.attributedText = muttext;
NSMutableParagraphStyle *paragraph=[[NSMutableParagraphStyle alloc]init];
paragraph.alignment=NSTextAlignmentCenter;//居中 NSDictionary* attrs =@{NSFontAttributeName:[UIFont fontWithName:@"AmericanTypewriter" size:],//文本的颜色 字体 大小
NSForegroundColorAttributeName:[UIColor redColor],//文字颜色
NSParagraphStyleAttributeName:paragraph,//段落格式
// NSBackgroundColorAttributeName:[UIColor blueColor],//背景色
NSStrokeWidthAttributeName:@, //描边宽度
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(, title.length)];
[title addAttribute:NSFontAttributeName value:SYSTEMFONT() range:NSMakeRange(, title.length)];
return title;
}
.如果只是静态显示textView的内容为设置的行间距,执行如下代码:

//    textview 改变字体的行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineSpacing = ;// 字体的行间距 NSDictionary *attributes = @{
NSFontAttributeName:[UIFont systemFontOfSize:],
NSParagraphStyleAttributeName:paragraphStyle
};
textView.attributedText = [[NSAttributedString alloc] initWithString:@"输入你的内容" attributes:attributes]; .如果是想在输入内容的时候就按照设置的行间距进行动态改变,那就需要将上面代码放到textView的delegate方法里 -(void)textViewDidChange:(UITextView *)textView { // textview 改变字体的行间距 NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = ;// 字体的行间距 NSDictionary *attributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:], 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 > ); if (textView.markedTextRange == nil && self.textLengthLimit > && 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 > ) {
CGFloat alpha = - (( - offsetY) / );
self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:alpha];
} else {
self.navigationController.navigationBar.backgroundColor = [color colorWithAlphaComponent:];
}
}

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":@};
[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 = ;
NSMutableArray *keys = [NSMutableArray new];
NSMutableArray *values = [NSMutableArray new];
for (int i = ; i < count; i++) {
NSString *key = @(i).description;
NSNumber *value = @(i);
[keys addObject:key];
[values addObject:value];
} //写入文件
for (int i = ; i < count; i++) {
[yykvFile saveItemWithKey:keys[i] value:[@"wujy" dataUsingEncoding:NSUTF8StringEncoding]
filename:keys[i] extendedData:nil];
} //读取
YYKVStorageItem *item = [yykvFile getItemForKey:keys[]];
NSString *aString = [[NSString alloc] initWithData:item.value encoding:NSUTF8StringEncoding];
NSLog(@"%@",aString); //写入数据库
for (int i = ; i < count; i++) {
[yykvSQLite saveItemWithKey:keys[i] value:[@"cnblogs" dataUsingEncoding:NSUTF8StringEncoding]];
} YYKVStorageItem *sqlitem = [yykvFile getItemForKey:keys[]];
NSString *asqlString = [[NSString alloc] initWithData:sqlitem.value encoding:NSUTF8StringEncoding];
NSLog(@"%@",asqlString);
}

6:打印所有注册的字体

#pragma mark - 打印系统所有已注册的字体名称
void enumerateFonts()
{
for(NSString *familyName in [UIFont familyNames])
{
NSLog(@"%@",familyName);
NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
for(NSString *fontName in fontNames)
{
NSLog(@"\t|- %@",fontName);
}
}
}

7:取图片某一像素点的颜色 在UIImage的分类中

- (UIColor *)colorAtPixel:(CGPoint)point
{
if (!CGRectContainsPoint(CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), point))
{
return nil;
} CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
int bytesPerPixel = ;
int bytesPerRow = bytesPerPixel * ;
NSUInteger bitsPerComponent = ;
unsigned char pixelData[] = {, , , }; CGContextRef context = CGBitmapContextCreate(pixelData,
,
,
bitsPerComponent,
bytesPerRow,
colorSpace,
kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextSetBlendMode(context, kCGBlendModeCopy); CGContextTranslateCTM(context, -point.x, point.y - self.size.height);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, self.size.width, self.size.height), self.CGImage);
CGContextRelease(context); CGFloat red = (CGFloat)pixelData[] / 255.0f;
CGFloat green = (CGFloat)pixelData[] / 255.0f;
CGFloat blue = (CGFloat)pixelData[] / 255.0f;
CGFloat alpha = (CGFloat)pixelData[] / 255.0f; return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

IOS开发基础知识--碎片30的更多相关文章

  1. IOS开发基础知识碎片-导航

    1:IOS开发基础知识--碎片1 a:NSString与NSInteger的互换 b:Objective-c中集合里面不能存放基础类型,比如int string float等,只能把它们转化成对象才可 ...

  2. IOS开发基础知识--碎片3

    十二:判断设备 //设备名称 return [UIDevice currentDevice].name; //设备型号,只可得到是何设备,无法得到是第几代设备 return [UIDevice cur ...

  3. IOS开发基础知识--碎片19

    1:键盘事件顺序 UIKeyboardWillShowNotification // 键盘显示之前 UIKeyboardDidShowNotification // 键盘显示完成后 UIKeyboar ...

  4. IOS开发基础知识--碎片33

    1:AFNetworking状态栏网络请求效果 直接在AppDelegate里面didFinishLaunchingWithOptions进行设置 [[AFNetworkActivityIndicat ...

  5. IOS开发基础知识--碎片42

    1:报thread 1:exc_bad_access(code=1,address=0x70********) 闪退 这种错误通常是内存管理的问题,一般是访问了已经释放的对象导致的,可以开启僵尸对象( ...

  6. IOS开发基础知识--碎片50

      1:Masonry 2个或2个以上的控件等间隔排序 /** * 多个控件固定间隔的等间隔排列,变化的是控件的长度或者宽度值 * * @param axisType 轴线方向 * @param fi ...

  7. IOS开发基础知识--碎片11

    1:AFNetwork判断网络状态 #import “AFNetworkActivityIndicatorManager.h" - (BOOL)application:(UIApplicat ...

  8. IOS开发基础知识--碎片14

    1:ZIP文件压缩跟解压,使用ZipArchive 创建/添加一个zip包 ZipArchive* zipFile = [[ZipArchive alloc] init]; //次数得zipfilen ...

  9. IOS开发基础知识--碎片16

    1:Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id) 对象在运行时获取其类型的能力称为内省.内省可以有多种方法实现. 判断对象类型 -(BOO ...

随机推荐

  1. JAVA--继承

    项目开发遇到一个问题,稀里糊涂给实现了,现在重点讨论一下这是个什么情况,大神们如果看到希望给点指点. 问题:子类与父类具有相同的属性和方法,将子类实例化为父类,调用对应属性的get.set方法,打印出 ...

  2. EntityFramework 7 Linq Contains In 奇怪问题

    这篇博文纪录一下:当使用 EF7,Linq 实现类似 where filename in('','','') SQL 代码,使用 Contains 出现报错问题. project.json 配置文件( ...

  3. Lua 学习笔记(五)函数

    函数的定义:在Lua中,函数是一种对语句和表达式进行抽象的主要机制. 一.函数基本用法        在Lua中,      1.函数既可以完成某项特定的任务.(被视为一条语句)      2.也可以 ...

  4. Oracle丢失重做日志的几种场景恢复

    实验环境:RHEL6.4 + Oracle 11.2.0.4 一.丢失重做日志组中成员 1.1 故障模拟 1.2 处理方法 1.3 实际处理过程 二.丢失重做日志组 2.1 丢失INACTIVE重做日 ...

  5. 实用的SQL语句

    行列互转 ) select * from test2 --列转行 select id,name,quarter,profile from test2 unpivot ( profile for qua ...

  6. Cesium原理篇:3最长的一帧之地形(4:重采样)

           地形部分的原理介绍的差不多了,但之前还有一个刻意忽略的地方,就是地形的重采样.通俗的讲,如果当前Tile没有地形数据的话,则会从他父类的地形数据中取它所对应的四分之一的地形数据.打个比方 ...

  7. [java] 更好的书写equals方法-汇率换算器的实现(4)

    [java] 更好的书写equals方法-汇率换算器的实现(4) // */ // ]]>   [java] 更好的书写equals方法-汇率换算器的实现(4) Table of Content ...

  8. xhtmlConformance与xhtml脚本呈现

    此配置节只有一个属性——mode,该特性为 ASP.NET 应用程序指定 XHTML 呈现模式.它包含三个值 要让此配置生效,需要把<pages>配置节中的controlRendering ...

  9. 设计模式(四)抽象工厂模式(Abstract Factory Pattern)

    一.引言 在上一专题中介绍了工厂方法模式,工厂方法模式是为了克服简单工厂模式的缺点而设计出来的,简单工厂模式的工厂类随着产品类的增加需要增加额外的代码,而工厂方法模式每个具体工厂类只完成单个实例的创建 ...

  10. failover机制的小讨论

    对于一个7*24小时无间断的线上服务来说,在服役时间内难免会遇到一些fail,例如db断开连接且短暂连接不上了, 下游的某个节点忽然挂了,运维部署上依赖的某一个东西不存在了等等场景.本文主要来讨论一下 ...