CALayer的简单应用

私彩视频开奖动画直播源码内部核心技术解析及修改可增加后台操控-持续更新文章! 其实在此很感谢能做出H5开奖系统的码农们,而我本人也喜欢分解此类的东西。 因为特殊原因,该东西本人就不做图片展示,以防他人商业化。 借用开奖摇奖代码首先分解首页index文件。代码如下:(后面持续在原有的作品上添加后台操作) 代码里写的//.....是我的注明代码的所需。 ​ <!DOCTYPE html> <html> <head> <... 阅读详情
If you’ve been programming for the iPhone, you’re probably really familiar with UIViews – buttons, text areas, sliders, web views, and more are all subclasses of UIView.

But you might not know much about the technology that UIView is built upon: CALayers! At least I didn’t, for quite a while.

It’s good to know a bit about CALayers, because you can use them to create some neat visual effects really easily. They’re also important to understand to work with Core Animation, which we’ll be discussing in a future tutorial.

In this tutorial, you’re going to learn the basics of using CALayers by making a simple app to create a layer and experiment with how it looks. In the process, you’ll learn what layers are, some neat properties you can set, and how to put images and custom-drawn content inside.

This tutorial assumes a basic familiarity with iPhone programming. If you are completely new, you might want to begin with the How To Create A Simple iPhone App Tutorial Series first.

So let’s get layering!

What Are CALayers?

CALayers are simply classes representing a rectangle on the screen with visual content.

“But wait a darn minute,” you may say, “that’s what UIViews are for!” That’s true, but there’s a trick to that: every UIView contains a root layer that it draws to! You can access this layer (created for you by default) with following bit of code:

CALayer *myLayer = myView.layer;

The neat thing about the CALayer class is that it contains a lot of properties that you can set on it to affect the visual appearance, such as:

  • The size and position of the layer
  • The layer’s background color
  • The contents of the layer (an image, or something drawn with Core Graphics)
  • Whether the corners of the layers should be rounded
  • Settings for applying a drop shadow to the layer
  • Applying a stroke around the edges of the layer
  • And much more!

You can use these properties to create some neat effects. For example, maybe you want to take an image, and put it in a white frame, and apply a shadow to it to make it look neat. Rather than whipping out Photoshop or creating a bunch of Core Graphics code, you can do this in a couple lines of code using CALayers!

The other neat thing about the properties on CALayer is that most of them are animatable. For example, you could start your image out with rounded corners, tap a button, and have it animate the corners back out to straight. This can make for some really neat effects!

You can use a CALayer on its own, or you can use one of the handy subclasses that are available, such as CAGradientLayer, CATextLayer, CAShapeLayer, and others. The default layer class for a UIView is the plain-old CALayer class, and that’s what you’ll be focusing on in this tutorial.

Getting Started

There’s no better way to understand using CALayers than to try them out yourself! So load up XCode, go to File\New Project, choose iOS\Application\View-based Application, and click “Choose…”. Name the project LayerFun, and click Save.

The View-based Application template starts with a single view controller, and as you know, each view controller has a root view. And as you learned above, every view has a root layer.

So now you’ll try this out for yourself by changing some properties on the view’s layer.

But first things first. To use CALayers and Core Animation, you need to use a framework that isn’t included by default in the View-based template: QuartzCore. So add it to your project by control-clicking the Frameworks group, selecting Add\Existing Framework…, and choosing QuartzCore.framework from the dropdown list.

Now that you’ve included QuartzCore, make the following changes to LayerFunViewController.m:

// Import QuartzCore.h at the top of the file#import <QuartzCore/QuartzCore.h> // Uncomment viewDidLoad and add the following linesself.view.layer.backgroundColor = [UIColor orangeColor].CGColor;self.view.layer.cornerRadius = 20.0;self.view.layer.frame =CGRectInset(self.view.layer.frame, 20, 20);

Let’s go over this bit by bit since this is new stuff:

  • To get a pointer to the layer for the view, you just use self.view.layer. Remember, you can the root view for a View Controller by calling self.view. Once you have the view, you can get its default layer (created automatically) by using view.layer. By default, the layer is a CALayer (not a subclass).
  • Next you set the layer’s background color to orange. Note that the backgroundColor property actually takes a CGColor, but it’s easy to convert a UIColor to a CGColor by using the CGColor property.
  • Next you round the corners a bit by setting the corner radius. The value you pass in is the radius of the circle which makes up the corner, and it chooses 20 here for a nice rounded edge.
  • Finally, you shrink the frame a bit so it’s easier to see, by using the handy CGRectInset function. The CGRectInset function takes a frame and an amount to shrink it by (for both the X and Y), and returns a new frame.

Compile and run your code, and you should see a rounded orange rectangle in the middle of your screen:

A Simple CALayer

CALayers and Sublayers

Just like UIViews can have subviews, CALayers can have sublayers as well. You can create a new CALayer very easily with the following line of code:

CALayer *sublayer = [CALayer layer];

Once you have a CALayer, you can set any properties on it you’d like. But remember there’s one property you definitely have to set: it’s frame (or bounds/position). After all, the layer needs to know how big it is (and where it’s located) in order to draw itself! When you’re done, you can add your new layer as a sublayer of another layer by the following line of code:

[myLayer addSublayer:sublayer];

Ok, now try this out for yourself by adding a simple sublayer to the view’s layer. Add the following lines of code inside viewDidLoad, right after where you left off last time:

CALayer *sublayer = [CALayer layer];sublayer.backgroundColor = [UIColor blueColor].CGColor;sublayer.shadowOffset = CGSizeMake(0, 3);sublayer.shadowRadius = 5.0;sublayer.shadowColor = [UIColor blackColor].CGColor;sublayer.shadowOpacity = 0.8;sublayer.frame = CGRectMake(30, 30, 128, 192);[self.view.layer addSublayer:sublayer];

This creates a new layer, and sets a few properties on it – including a few you haven’t seen before to set shadows. You can see here how easy it is to set shadows on a layer – which can give some amazing effects with very little effort!

After setting the properties, it sets the frame of the layer and adds it as a sublayer to the view’s layer. Remember that these coordinates are relative to the parent layer’s frame, and since the parent layer begins at (20,20), the sublayer will be offset an additional (30,30) from that, so on the screen it will be at (50,50).

Compile and run your code, and you should now see a blue sublayer on the screen!

A CALayer Sublayer with a Shadow

Setting CALayer Image Content

One of the coolest things about CALayers is that they can contain more than just plain colors. It’s extremely easy to have them contain images instead, for example.

So let’s replace the blue sublayer with an image instead. You can take a Default.jpg from one of your iPhone apps to use as a test, or you can download a splash screen from one of my apps.

Add the splash screen to your project, and inside viewDidLoad right before the last line you added that adds the sublayer to self.view.layer, add the following lines of code:

sublayer.contents = (id) [UIImage imageNamed:@"BattleMapSplashScreen.jpg"].CGImage;sublayer.borderColor = [UIColor blackColor].CGColor;sublayer.borderWidth = 2.0;

This sets the contents of the layer to an image (that’s literally all it takes!) and also sets the borderColor and borderWidth to set up a black stroke around the edges, to demonstrate how that works.

Compile and run your code, and you should now see the blue layer’s contents replaced with your splash screen image!

A CALayer with Image Content

A Note about Corner Radius and Image Content

Now that you have this working, you might think it would be cool to round the corners of the splash screen as well, by setting the cornerRadius.

Well the problem is that as far as I can tell, if you set that on a CALayer with image contents, the image will still be drawn outside the corner radius boundary. You can solve this by setting sublayer.masksToBounds to YES, but if you do that the shadows won’t show up because they’ll be masked out!

I found a workaround by creating two layers. The outer layer is just a colored CALayer with a border and a shadow. The inner layer contains the image, and is also rounded but set up to mask. That way, the outer layer can draw the shadow, and the inner layer can contain the image.

Try this out by modifying the code to create the sublayer as follows:

CALayer *sublayer = [CALayer layer];sublayer.backgroundColor = [UIColor blueColor].CGColor;sublayer.shadowOffset = CGSizeMake(0, 3);sublayer.shadowRadius = 5.0;sublayer.shadowColor = [UIColor blackColor].CGColor;sublayer.shadowOpacity = 0.8;sublayer.frame =CGRectMake(30, 30, 128, 192);sublayer.borderColor = [UIColor blackColor].CGColor;sublayer.borderWidth = 2.0;sublayer.cornerRadius = 10.0;[self.view.layer addSublayer:sublayer]; CALayer *imageLayer = [CALayer layer];imageLayer.frame = sublayer.bounds;imageLayer.cornerRadius =10.0;imageLayer.contents = (id) [UIImage imageNamed:@"BattleMapSplashScreen.jpg"].CGImage;imageLayer.masksToBounds = YES;[sublayer addSublayer:imageLayer];

Compile and run your code, and now your image will have rounded corners!

A CALayer with Image Content and Corner Radius

CALayer and Custom Drawn Content

If you want to custom-draw the contents of a layer with Core Graphics instead of putting an image inside, that is quite easy too.

The idea is you set a class as the delegate of the layer, and that class needs to implement a method named drawLayer:inContext. This can contain Core Graphics drawing code to draw anything you want in that space.

Let’s try this out by adding a new layer, and drawing a pattern inside it. You’ll set the view controller as the delegate of the layer, and implement the drawLayer:inContext method to draw the pattern. As for the pattern drawing code, you’ll be using the same code as in the Core Graphics 101: Patternstutorial posted earlier on this site.

Add the following code at the bottom of your viewDidLoad to add a new layer that will be custom drawn:

CALayer *customDrawn = [CALayer layer];customDrawn.delegate = self;customDrawn.backgroundColor = [UIColor greenColor].CGColor;customDrawn.frame = CGRectMake(30, 250, 128, 40);customDrawn.shadowOffset = CGSizeMake(0, 3);customDrawn.shadowRadius = 5.0;customDrawn.shadowColor = [UIColor blackColor].CGColor;customDrawn.shadowOpacity =0.8;customDrawn.cornerRadius = 10.0;customDrawn.borderColor = [UIColor blackColor].CGColor;customDrawn.borderWidth =2.0;customDrawn.masksToBounds = YES;[self.view.layer addSublayer:customDrawn];[customDrawn setNeedsDisplay];

Most of the code here you’ve seen before (creating a layer, setting properties such as shadow/cornerRadius/border/masksToBounds), however there are two new pieces:

  1. First, it sets the delegate of the layer to self. This means that this object (self) will need to implement the drawLayer:inContext method to draw the contents of the layer.
  2. Second, after it adds the layer, it needs to tell the layer to refresh itself (and call drawLayer:inContext) by calling setNeedsDisplay. If you forget to call this, drawLayer:inContext will never be called, so the pattern won’t show up!

Next add the code to implement drawLayer:inContext, as shown below:

void MyDrawColoredPattern (void *info, CGContextRef context) {  CGColorRef dotColor = [UIColor colorWithHue:0 saturation:0 brightness:0.07alpha:1.0].CGColor; CGColorRef shadowColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.1].CGColor;  CGContextSetFillColorWithColor(context, dotColor); CGContextSetShadowWithColor(context, CGSizeMake(0, 1), 1, shadowColor);  CGContextAddArc(context, 3, 3, 4, 0, radians(360), 0); CGContextFillPath(context);  CGContextAddArc(context, 16, 16, 4, 0, radians(360), 0); CGContextFillPath(context); } - (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {  CGColorRef bgColor = [UIColor colorWithHue:0.6 saturation:1.0 brightness:1.0 alpha:1.0].CGColor; CGContextSetFillColorWithColor(context, bgColor); CGContextFillRect(context, layer.bounds);   static const CGPatternCallbacks callbacks = { 0, &MyDrawColoredPattern, NULL };  CGContextSaveGState(context); CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); CGContextSetFillColorSpace(context, patternSpace); CGColorSpaceRelease(patternSpace);  CGPatternRef pattern = CGPatternCreate(NULL, layer.bounds, CGAffineTransformIdentity, 24,  24, kCGPatternTilingConstantSpacing,  true,  &callbacks); CGFloat alpha = 1.0; CGContextSetFillPattern(context, pattern, &alpha); CGPatternRelease(pattern); CGContextFillRect(context, layer.bounds); CGContextRestoreGState(context);}

This code is literally copied and pasted from the Core Graphics 101: Patterns tutorial (just with a different color, and using the passed in context and layer bounds), so we aren’t going to cover it again here. If you want to know what it does, refer to the above tutorial.

That’s it! Compile and run the code, and you should now see a blue grip pattern below the image.

Where To Go From Here?

Here is a sample project with all of the code we’ve developed in the above tutorial.

At this point, you should be familiar with the concepts of CALayers and how to create some neat effects with them really easily. In future tutorials, I’ll show you how you can animate CALayers using Core Animation, and use some really handy subclasses of CALayer such as CAGradientLayer, CATextLayer, and CAShapeLayer.

In the meantime, check out the Core Animation Programming Guide, which does a great job talking about Core Animation, and more details about CALayers.

If you’ve found some good ways to use CALayers in your projects, please share below! :]

QT+OSG/osgEarth编译之七十六:gltf+Qt编译(一套代码、一套框架,跨平台编译,版本:osgEarth-3.3插件库osgdb_gltf) 通过一套gltf代码和框架,实现osgdb_gltf跨平台编译。 在Qt环境下,集成头文件、库文件,构建跨平台编译的pro文件。 通过构建的一套配置工程,基于Qt Creator IDE,完成跨平台的编译实践。 在Windows、Linux、MacOS等操作系统上进行测试,成功编译,形成的成果(头文件、库文件等)可在不同系统下调用或使用,从而更好地构建跨平台解决方案。 采用的是osgEarth3.3版本。 读者可参考博客中的集成原理,构建不同版本的osgdb_gltf跨平台包。 阅读详情

相关推荐

Nginx反向代理MinIO私有桶签名失效?一招解决Host头校验问题

本文详细解析了Nginx反向代理MinIO私有桶时出现的签名失效问题,重点解决了Host头校验导致的"SignatureDoesNotMatch"错误。通过精准配置proxy_set_header保持Host头一致性,并提供了二级目录代理和调试指南,帮助开发者高效解决这一常见技术难题。

weixin_29201313的博客 320

Introduction to CALayers Tutorial

http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial If you’ve been programming for the iPhone, you’re probably really familiar with UIViews – buttons, text areas, sliders, w

454

Kettle Web版部署指南

看到以上的日志则表示启动成功。

2401_89221867的博客 1716

CALayer 简单的使用

转:http://www.raywenderlich.com/2502/introduction-to-calayers-tutorial If you’ve been programming for the iPhone, you’re probably really familiar with UIViews – buttons, text areas, sliders, web vie...

weixin_30670151的博客 189

从零开始安装pytorch(包含GPU和CPU版本的安装)

Pytorch是。

qiaoxinyu1989的博客 8万+

雨流计数法的matlab实现,采用三点法与四点法

介绍雨流计数法是20世纪50年代由英国的两位工程师M.Matsuishi和T.Endo提出来的。该计数法的主要功能是把实测载荷历程简化为若干个载荷循环,供疲劳寿命估算和编制疲劳试验载荷谱使用。它以双参数法为基础,考虑了动强度(幅值)和静强度(均值)两个变量,符合疲劳载荷本身固有的特性。雨流计数法主要用于工程界,特别在疲劳寿命计算中运用非常广泛计数规则(1)雨流依次从载荷时间历程的峰值位置的内侧沿着...

u011391128的博客 3万+

iOS Layer层相关,图片裁剪与形变

1,创建Layer层,并添加到当前视图的Layer层上,及相关属性 1,创建图层layer CALayer *layer1 = [[CALayer alloc] init]; 将创建的layer添加到当前视图的layer层上 [self.view.layer addSublayer:layer1]; // 设置属性 // 1,设置位置 // 中心点的位置

小郭的博客 3337

VR大空间开发前期,设备选项与流程

欢迎开发者加入 VR 大空间开发之旅!本系列教程将以 Pico 和 HTC 设备为核心,系统拆解从基础搭建到功能实现的全流程,助你快速掌握开发要点。本系列共 12 篇,专为有编程基础但缺乏大空间开发经验的开发者设计。前 7 篇针对 Pico 和 HTC 设备差异分别讲解,后续步骤通用。核心目录如下:​1. 空间环境要求 - 灯光设置 - 场地面积规划 - 识别图案设计2. 网络部署方案3. 客户端体验模式解析 - 一体机模式 - 云渲染模式 - 背包体验模式4. Pico空间录制方法

unitygroup的博客 1348

CALayer简单应用 —— 阴影

#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) CALayer *imageLayer; @property (nonatomic, strong) UIImage *image; @end @implementation ViewController

Escape This Moment 1174

手把手教你学Simulink——基于经典PID控制的电机系统场景实例:BLDC电机PID电流控制策略仿真

*无刷直流电机(Brushless DC Motor, BLDC)**因其高效率、长寿命和低维护成本,在众多领域如家用电器、工业自动化、电动汽车等得到了广泛应用。为了实现对BLDC电机的有效控制,通常采用基于霍尔传感器或反电动势检测的换相技术,并结合电流闭环控制以提高系统的动态响应和稳定性。本教程将带你使用构建一个基于PID控制的BLDC电机电流控制策略仿真模型BLDC电机建模PID控制器设计与应用系统仿真与调试控制效果分析本文介绍了如何使用构建一个。

MHD0815的博客 196

YOLOv9改进策略【损失函数篇】| Slide Loss,解决简单样本和困难样本之间的不平衡问题

本文记录的是改进YOLOv9的损失函数,将其替换成Slide Loss,并详细说明了优化原因,注意事项等。Slide Loss函数可以有效地解决样本不平衡问题,为困难样本赋予更高的权重,使模型在训练过程中更加关注困难样本。若是在自己的数据集中发现容易样本的数量非常大,而困难样本相对稀疏,可尝试使用Slide Loss来提高模型在处理复杂样本时的性能。

Limiiiing的博客 2594

CALayer简单应用

http://www.cocoachina.com/iphonedev/sdk/2011/0930/3303.html 本文由论坛会员jiang1590分享 前一阵子读到一篇介绍CALayer(这里简单地称其为层)的教程,比较简单易懂,适合初学者,我在这里就不完全翻译了,只是把要点说明一下。 首先要说的是CALayers 是屏幕上的一个具有可见内容的矩形...

weixin_33772645的博客 94

uniapp - web-view嵌套H5网页白屏问题,<web-view>页面跳转出现白屏情况,强力解决uniapp嵌套webview页面时出现无法加载并白屏(无论本地还是线上H5网页链接都能解决)

uniapp微信小程序,uniapp APP端,uni-app web-view嵌套H5项目白屏问题分析及解决,uniapp嵌套webview页面时,出现白屏,uniapp <web-view>页面跳转出现白屏解决方法,uniapp <web-view>页面跳转出现白屏解决方法,解决uniapp的web-view打开网页在老手机上出现白屏的问题,uni-app web-view白屏处理,引入本地网页白屏,WebView 加载不出网页,一片空白webview白屏加载不出来,使用webview加载链接后白屏,u

🏆 前端领域优质创作者 1万+

Calayer简单应用——下载进度条

封装一个UIView内含有一个CAlayer属性(隐式动画) #import @interface ProgressView : UIView @property (nonatomic, assign) float progress; @end ************************************************

Escape This Moment 1164

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

CALayer 简单操作和实际应用

1、CALayer //每一个UIView,都存在一个CALayer.(主层) //CALayer的功能 描边,圆角,阴影。。。 //CALayer 属于QuartzCore绘图框架 //明明有UIColor,为啥用CGColorRef?CGColorRef属于QuartzCore,可以使用在mac上。 UIImageView* imageView = [[UII...

123

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

CALayer简单应用——渐变

#import "ViewController.h" @interface ViewController () @property (nonatomic, strong) CALayer *imageLayer; @end @implementation ViewController - (void)viewDidLoad {     [super viewDi

Escape This Moment 1054

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

CALayer简单应用——隐式动画

#import "ViewController.h" #define figureWidth 50 @interface ViewController () @property (nonatomic, strong) CALayer *graph; @end @implementation ViewController - (void)viewDi

Escape This Moment 921

CALayer简单应用——带阴影的icon

原理:正常情况下是在一个图层上既设置icon,也设置阴影就能达到要求;但是这样做会发现阴影不见了...。原因是设置圆形图层需要把暴露在该图层外的子图层部分切割掉( self.iconLayer.masksToBounds = YES;)   在设置图片时会重新绘制一个图层来装图片(被切割后就变成圆的了),而阴影自然也是属于在该图层外的部分,顺理成章的也被切割掉了....  。所以要同时实现这两

Escape This Moment 1000

CALayer 和 CAGradientLayer简单使用

CALayer   CALayer 是一个很经常使用的到的 Object,很常用,也很重要,同时又有比较多的属性,嗯,一定要详细了解下。 CALayer 的原理很难懂,由于我目前只注重运用,所以就说那些在实际开发中能用到的一些地方。 如果要更改 UIView 的 CALayer,要引用:#import . 下面先推荐两篇文章: 文章 1:原理介绍的比较详细; 2:官方文

王正魁 638

CALayer简单教程

http://www.iphone-geek.cn/编程/calayer简单教程

programmerboymxd的专栏 1813

CALayer使用2

转自  http://www.cnblogs.com/mjios/archive/2013/04/14/3019728.html 本文目录 一、添加一个简单的图层二、添加一个显示图片的图层三、为什么CALayer中使用CGColorRef和CGImageRef这2种数据类型,而不用UIColor和UIImage?四、UIView和CALayer的选择五、UIView

1456

CALayer之旅(CALayer Tutorial: Getting Started)

CALayer之旅(CALayer Tutorial: Getting Started)Note:如果你没有上面我们所说的那些基础,没关系,我们有不少关于CALayer的教程和书籍,比如:Learn to Code iOS Apps with Swift和 The iOS Apprentice。### 开篇(Getting Started) 要想学习layer,最简单的方法就是在实践中去使用它,所

dubai 1339

6-闪耀的激光-CALayer 的应用

##开始 最近项目中需要实现一个名片扫描的功能,这会用到一个让用户等待名片识别结果的界面。界面非常简单,让一条绿色的激光不停地在名片上上下移动,模拟扫描仪正在工作的样子。 这么简单的 UI,完全可以抛开美工和切图,一个人用 Core Grahics 来实现!而且这次要检验我们之前的学习成果! 绘制4个角 首先我们在窗口的 4 个角上绘制直角图形,用于表示镜头的取景框。首先绘制第一个角。只要绘制出第一个角,其它 3 个角无非是在它的基础上旋转一定角度而已。 首先声明变量: var borderColo

kmyhy的专栏 572

CALayer2-创建新的层

* 上一讲已经说过,UIView内部默认有个CALayer对象(层),通过layer属性可以访问这个层。要注意的是,这个默认的层不允许重新创建,但可以往层里面添加子层 * UIView可以通过addSubview:方法添加子视图,类似地,CALayer可以通过addSublayer:方法添加子层 接下来演示一下如何添加子层: 回到顶部 一、添加一个简单的图层 1

lee89757的博客 363

CALayer

2019独角兽企业重金招聘Python工程师标准>>> ...

weixin_33898876的博客 100
上一篇: IOS7获取唯一标识UDID
下一篇: php定时器
临红尘
博客等级 码龄19年 10粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值