图片裁剪
第一种:获取图片原大小,按图片原大小裁剪图片(UIImage转化为CGImageRef进行裁剪)
//获取图片
UIImage *image = [UIImage imageNamed:@"图片名字"];
//获取图片的大小
CGSize size = image.size;
//设置需要剪切的部分(按照原图片的大小进行)
CGRect rect = CGRectMake(0, 0, size.width / 5, size.height);
//转化为CGImageRef
CGImageRef sourceImageRef = [image CGImage];
//进行裁剪
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);
//转化为UIImage
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
//释放内存
CGImageRelease(newImageRef);
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(10, 20, 300, 300);
imageView.image = newImage;
[self.view addSubview:imageView];
第二种:使用CALayer属性对图片进行裁剪(示例:把一张图片裁剪成了九张)
int width = 80;
int height = 100;
int sapce = 1;
for(int i = 0; i < 9; i++)
{
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(60 + (width + sapce) * (i%3), 80 + (height + sapce) * (i/3), width, height);
view.backgroundColor = [UIColor redColor];
//设置层的内容
view.layer.contents = (__bridge id _Nullable)([UIImage imageNamed:@"图片名字"].CGImage);
//设置图片剪切的范围 [0,1]
view.layer.contentsRect = CGRectMake(1.0/3.0 * (i%3), 1.0/3.0 * (i/3), 1.0/3.0, 1.0/3.0);
[self.view addSubview:view];
}
图片添加水印
创建一个类别会方便使用
下面是图片添加水印的方法,使用的是图片上下文来实现的,这是在类别的.m文件中。
#import "UIImage+Watermark.h"
//设置水印字体大小
#define kFontSize 17
//设置水印字体颜色
#define kFontColor greenColor
@implementation UIImage (Watermark)
- (UIImage *)watermarkWithText:(NSString *)text
{
//开启图片上下文
UIGraphicsBeginImageContextWithOptions(self.size, YES, 0);
[self drawInRect:CGRectMake(0, 0, self.size.width, self.size.height)];
//设置水印
NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.alignment = NSTextAlignmentRight;
[text drawInRect:CGRectMake( 0, self.size.height - 30, self.size.width - 10, 30) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:kFontSize],NSParagraphStyleAttributeName:paragraph,NSForegroundColorAttributeName:[UIColor kFontColor]}];
//获取图片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//结束上下文
UIGraphicsEndImageContext();
return image;
}
@end
写完后只要写一行代码就可以实现水印的添加,如:
UIImageView *imageView = [[UIImageView alloc] init];
imageView.frame = self.view.bounds;
UIImage *image = [UIImage imageNamed:@"图片名字"];
//添加水印
UIImage *newImage = [image watermarkWithText:@"ssssss水印"];
imageView.image = newImage;
[self.view addSubview:imageView];
注意:水印添加时,是按图片的大小进行的,所以图片太大,显示的水印会变的很小,图片很小,显示出来的水印会变的很大,所以需要自己调整。
网友评论