iOS开发之Quartz2D的介绍与使用详解

2020-01-18 22:02:02王冬梅

注:

如果想实现点击以下变换颜色可以加上如下代码:


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
 
 //重绘
 [self setNeedsDisplay];
 
}

8、绘制文字


- (void)drawRect:(CGRect)rect {
 
 NSString *str = @"李峰峰博客:http://www.easck.com/";
 
 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 //设置字体
 dict[NSFontAttributeName] = [UIFont systemFontOfSize:30];
 //设置颜色
 dict[NSForegroundColorAttributeName] = [UIColor redColor];
 //设置描边
 dict[NSStrokeColorAttributeName] = [UIColor blueColor];
 dict[NSStrokeWidthAttributeName] = @3;
 //设置阴影
 NSShadow *shadow = [[NSShadow alloc] init];
 shadow.shadowColor = [UIColor greenColor];
 shadow.shadowOffset = CGSizeMake(-2, -2);
 shadow.shadowBlurRadius = 3;
 dict[NSShadowAttributeName] = shadow;
 
 //设置文字的属性
 //drawAtPoint不会自动换行
 //[str drawAtPoint:CGPointMake(0, 0) withAttributes:dict];
 //drawInRect会自动换行
 [str drawInRect:self.bounds withAttributes:dict];
 
}

运行效果:

ios,quartz2d,详解,quartz2d教程

9、加水印


//
// ViewController.m
// Quartz2DTest
//
// Created by 李峰峰 on 2017/2/6.
// Copyright © 2017年 李峰峰. All rights reserved.
//
 
#import "ViewController.h"
#import "MyView.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
 [super viewDidLoad];
 
 UIImageView *myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
 [self.view addSubview:myImageView];
 
 
 //生成一张图片
 //0.加载图片
 UIImage *oriImage = [UIImage imageNamed:@"test"];
 //1.创建位图上下文(size:开启多大的上下文,就会生成多大的图片)
 UIGraphicsBeginImageContext(oriImage.size);
 //2.把图片绘制到上下文当中
 [oriImage drawAtPoint:CGPointZero];
 //3.绘制水印(虽说UILabel可以快速实现这种效果,但是我们也可以绘制出来)
 NSString *str = @"李峰峰博客";
 
 
 NSMutableDictionary *dict = [NSMutableDictionary dictionary];
 dict[NSFontAttributeName] = [UIFont systemFontOfSize:20];
 dict[NSForegroundColorAttributeName] = [UIColor redColor];
 
 [str drawAtPoint:CGPointZero withAttributes:dict];
 //4.从上下文当中生成一张图片
 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
 //5.关闭位图上下文
 UIGraphicsEndImageContext();
 
 
 myImageView.image = newImage;
 
}
 
@end

运行效果:

ios,quartz2d,详解,quartz2d教程