OS手势识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势)

【手势识别-UIPinchGestureRecognizer捏合-UIPanGestureRecognizer缩放 Objective-C语言】 阅读详情

1、UIGestureRecognizer介绍
手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。

 

iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了UIGestureRecognizer类。手势识别UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。

 

UITapGestureRecognizer  
UIPinchGestureRecognizer
UIRotationGestureRecognizer
UISwipeGestureRecognizer
UIPanGestureRecognizer
UILongPressGestureRecognizer

 

上面的手势对应的操作是: 
Tap(点一下)
Pinch(二指往內或往外拨动,平时经常用到的缩放)
Rotation(旋转)
Swipe(滑动,快速移动)
Pan (拖移,慢速移动)
 LongPress(长按)
UIGestureRecognizer的继承关系如下:
 

2、使用手势的步骤
使用手势很简单,分为两步:


1)创建手势实例。当创建手势时,指定一个回调方法,当手势开始,改变、或结束时,回调方法被调用。
2)添加到需要识别的View中。每个手势只对应一个View,当屏幕触摸在View的边界内时,如果手势和预定的一样,那就会回调方法。

ps:一个手势只能对应一个View,但是一个View可以有多个手势。建议在真机上运行这些手势,模拟器操作不太方便,可能导致你认为手势失效。

 

3、Pan 拖动手势:
1.UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];  
2.snakeImageView.frame = CGRectMake(50, 50, 100, 160);  
3.UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]  
4.                                                initWithTarget:self  
5.                                                action:@selector(handlePan:)];      
6.[snakeImageView addGestureRecognizer:panGestureRecognizer];  
7.[self.view setBackgroundColor:[UIColor whiteColor]];  
8.[self.view addSubview:snakeImageView]; 


新建一个ImageView,然后添加手势
回调方法:
1.- (void) handlePan:(UIPanGestureRecognizer*) recognizer  
2.{  
3.    CGPoint translation = [recognizer translationInView:self.view];  
4.    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,  
5.                                   recognizer.view.center.y + translation.y);  
6.    [recognizer setTranslation:CGPointZero inView:self.view];  
7.      
8.} 

 

4、Pinch缩放手势
1.UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]  
2.                                                        initWithTarget:self  
3.                                                        action:@selector(handlePinch:)];<P class=p1>[<SPAN   class=s1>snakeImageView</SPAN> <SPAN class=s2>addGestureRecognizer</SPAN>:pinchGestureRecognizer];</P>


1.- (void) handlePinch:(UIPinchGestureRecognizer*) recognizer  
2.{  
3.    recognizer.view.transform = CGAffineTransformScale(recognizer.view.transform, recognizer.scale, recognizer.scale);  
4.    recognizer.scale = 1;  
5.}    


5、Rotation旋转手势
1.UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]  
2.                                                 initWithTarget:self  
3.                                                 action:@selector(handleRotate:)];  
4.[snakeImageView addGestureRecognizer:rotateRecognizer]; 


1.- (void) handleRotate:(UIRotationGestureRecognizer*) recognizer  
2.{  
3.    recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, recognizer.rotation);  
4.    recognizer.rotation = 0;  
5.} 


 

添加了这几个手势后,运行看效果,程序中的imageView放了一个这样的图片
                    /^\/^\
                  _|__|  O|
         \/     /~     \_/ \
          \____|__________/  \
                 \_______      \
                         `\     \                 \
                           |     |                  \
                          /      /                    \
                         /     /                       \\
                       /      /                         \ \
                      /     /                            \  \
                    /     /             _----_            \   \
                   /     /           _-~      ~-_         |   |
                  (      (        _-~    _--_    ~-_     _/   |
                   \      ~-____-~    _-~    ~-_    ~-_-~    /
                     ~-_           _-~          ~-_       _-~   
                        ~--______-~                ~-___-~
在模拟器上拖动是没问题的。缩放和旋转有点问题,估计是因为在模拟器上的模拟的两个接触点距离在imageView的边界外了,所以操作无效果。建议在真机上运行这个手势。

 

在模拟器上缩放和选择的操作技巧:可以把imageView的frame值设置大一点,按住alt键,按下触摸板(不按下不行),这样就可以旋转和缩放了。


6、添加第二个ImagView并添加手势
记住:一个手势只能添加到一个View,两个View当然要有两个手势的实例了。

- (void)viewDidLoad  
{  
    [super viewDidLoad];  
  
    UIImageView *snakeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"snake.png"]];  
    UIImageView *dragonImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dragon.png"]];  
    snakeImageView.frame = CGRectMake(120, 120, 100, 160);  
    dragonImageView.frame = CGRectMake(50, 50, 100, 160);  
    [self.view addSubview:snakeImageView];  
    [self.view addSubview:dragonImageView];  
      
    for (UIView *view in self.view.subviews) {  
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc]  
                                                        initWithTarget:self  
                                                        action:@selector(handlePan:)];  
          
        UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc]  
                                                            initWithTarget:self  
                                                            action:@selector(handlePinch:)];  
          
        UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]  
                                                         initWithTarget:self  
                                                         action:@selector(handleRotate:)];  
          
        [view addGestureRecognizer:panGestureRecognizer];  
        [view addGestureRecognizer:pinchGestureRecognizer];  
        [view addGestureRecognizer:rotateRecognizer];  
        [view setUserInteractionEnabled:YES];  
    }  
    [self.view setBackgroundColor:[UIColor whiteColor]];       
} 


多添加了一条龙的view,两个view都能接收上面的三种手势。运行效果如下:

7、拖动(pan手势)速度(以较快的速度拖放后view有滑行的效果)

如何实现呢?
1)监视手势是否结束
2)监视触摸的速度

- (void) handlePan:(UIPanGestureRecognizer*) recognizer  
{  
    CGPoint translation = [recognizer translationInView:self.view];  
    recognizer.view.center = CGPointMake(recognizer.view.center.x + translation.x,  
                                       recognizer.view.center.y + translation.y);  
    [recognizer setTranslation:CGPointZero inView:self.view];  
      
    if (recognizer.state == UIGestureRecognizerStateEnded) {  
          
        CGPoint velocity = [recognizer velocityInView:self.view];  
        CGFloat magnitude = sqrtf((velocity.x * velocity.x) + (velocity.y * velocity.y));  
        CGFloat slideMult = magnitude / 200;  
        NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);  
          
        float slideFactor = 0.1 * slideMult; // Increase for more of a slide   
        CGPoint finalPoint = CGPointMake(recognizer.view.center.x + (velocity.x * slideFactor),  
                                         recognizer.view.center.y + (velocity.y * slideFactor));  
        finalPoint.x = MIN(MAX(finalPoint.x, 0), self.view.bounds.size.width);  
        finalPoint.y = MIN(MAX(finalPoint.y, 0), self.view.bounds.size.height);  
          
        [UIView animateWithDuration:slideFactor*2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{  
            recognizer.view.center = finalPoint;  
        } completion:nil];  
          
    }  
    

代码实现解析:
1)计算速度向量的长度(估计大部分都忘了)这些知识了。
2)如果速度向量小于200,那就会得到一个小于的小数,那么滑行会很短
3)基于速度和速度因素计算一个终点
4)确保终点不会跑出父View的边界
5)使用UIView动画使view滑动到终点


运行后,快速拖动图像view放开会看到view还会在原来的方向滑行一段路。


8、同时触发两个view的手势
手势之间是互斥的,如果你想同时触发蛇和龙的view,那么需要实现协议
UIGestureRecognizerDelegate,
@interface ViewController : UIViewController<UIGestureRecognizerDelegate>  
@end 

 

并在协议这个方法里返回YES。
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer  
{  
    return YES;  
} 


把self作为代理设置给手势:
panGestureRecognizer.delegate = self;  
pinchGestureRecognizer.delegate = self;  
rotateRecognizer.delegate = self; 

这样可以同时拖动或旋转缩放两个view了。

 

9、tap点击手势
这里为了方便看到tap的效果,当点击一下屏幕时,播放一个声音。为了播放声音,我们加入AVFoundation.framework这个框架。
- (AVAudioPlayer *)loadWav:(NSString *)filename {  
    NSURL * url = [[NSBundle mainBundle] URLForResource:filename withExtension:@"wav"];  
    NSError * error;  
    AVAudioPlayer * player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];  
    if (!player) {  
        NSLog(@"Error loading %@: %@", url, error.localizedDescription);  
    } else {  
        [player prepareToPlay];  
    }  
    return player;  
} 


我会在最后例子代码给出完整代码,添加手势的步骤和前面一样的。

1.#import <UIKit/UIKit.h>   
2.#import <AVFoundation/AVFoundation.h>   
3.  
4.@interface ViewController : UIViewController<UIGestureRecognizerDelegate>  
5.@property (strong) AVAudioPlayer * chompPlayer;  
6.@property (strong) AVAudioPlayer * hehePlayer;  
7.  
8.@end 

 

运行,点一下某个图,就会播放一个咬东西的声音。不过这个点击播放声音有点缺陷,就是在慢慢拖动的时候也会播放。这使得两个手势重合了。怎么解决呢?使用手势的:requireGestureRecognizerToFail方法。

 

10、手势的依赖性

在viewDidLoad的循环里添加这段代码:
[tapRecognizer requireGestureRecognizerToFail:panGestureRecognizer]; 

 

意思就是,当如果pan手势失败,就是没发生拖动,才会出发tap手势。这样如果你有轻微的拖动,那就是pan手势发生了。tap的声音就不会发出来了。


11、自定义手势
自定义手势继承:UIGestureRecognizer,实现下面的方法:
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:

 

新建一个类,继承UIGestureRecognizer,代码如下:

.h文件

#import <UIKit/UIKit.h>
typedef enum {
    DirectionUnknown = 0,
    DirectionLeft,
    DirectionRight
} Direction;

@interface HappyGestureRecognizer : UIGestureRecognizer
@property (assign) int tickleCount;
@property (assign) CGPoint curTickleStart;
@property (assign) Direction lastDirection;

@end

 

.m文件

#import "HappyGestureRecognizer.h"   
#import <UIKit/UIGestureRecognizerSubclass.h>   
#define REQUIRED_TICKLES        2   
#define MOVE_AMT_PER_TICKLE     25   
  
@implementation HappyGestureRecognizer  
  
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {  
    UITouch * touch = [touches anyObject];  
    self.curTickleStart = [touch locationInView:self.view];  
}  
  
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {  
      
    // Make sure we've moved a minimum amount since curTickleStart   
    UITouch * touch = [touches anyObject];  
    CGPoint ticklePoint = [touch locationInView:self.view];  
    CGFloat moveAmt = ticklePoint.x - self.curTickleStart.x;  
    Direction curDirection;  
    if (moveAmt < 0) {  
        curDirection = DirectionLeft;  
    } else {  
        curDirection = DirectionRight;  
    }  
    if (ABS(moveAmt) < MOVE_AMT_PER_TICKLE) return;  
      
    // 确认方向改变了   
    if (self.lastDirection == DirectionUnknown ||  
        (self.lastDirection == DirectionLeft && curDirection == DirectionRight) ||  
        (self.lastDirection == DirectionRight && curDirection == DirectionLeft)) {  
          
        // 挠痒次数   
        self.tickleCount++;  
        self.curTickleStart = ticklePoint;  
        self.lastDirection = curDirection;  
          
        // 一旦挠痒次数超过指定数,设置手势为结束状态   
        // 这样回调函数会被调用。   
        if (self.state == UIGestureRecognizerStatePossible && self.tickleCount > REQUIRED_TICKLES) {  
            [self setState:UIGestureRecognizerStateEnded];  
        }  
    }  
      
}  
  
- (void)reset {  
    self.tickleCount = 0;  
    self.curTickleStart = CGPointZero;  
    self.lastDirection = DirectionUnknown;  
    if (self.state == UIGestureRecognizerStatePossible) {  
        [self setState:UIGestureRecognizerStateFailed];  
    }  
}  
  
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    [self reset];  
}  
  
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event  
{  
    [self reset];  
}  
  
@end 


调用自定义手势和上面一样,回到这样写:
- (void)handleHappy:(HappyGestureRecognizer *)recognizer{
    [self.hehePlayer play];
}

手势成功后播放呵呵笑的声音。在真机上运行,按住某个view,快速左右拖动,就会发出笑的声音了。


代码解析:
先获取起始坐标:curTickleStart
通过和ticklePoint的x值对比,得出当前的放下是向左还是向右。再算出移动的x的值是否比MOVE_AMT_PER_TICKLE距离大,如果太则返回。
再判断是否有三次是不同方向的动作,如果是则手势结束,回调。

参考:http://www.raywenderlich.com/6567/uigesturerecognizer-tutorial-in-ios-5-pinches-pans-and-more
例子代码:http://download.youkuaiyun.com/detail/totogo2010/5094059

 

来源:容芳志的博客

UIGestureRecognizer手势识别详解 iOS应用开发过程,合理的使用手势识别功能来响应用户的操作,能够很好提升用户体验,为App增色。下面对UIGestureRecognizer手势进行一个比较全面的描述:      1、UIGestureRecognizer介绍            UIGestureRecognizer是手势识别的一个抽象类,没法直接使用。好心的苹果大神们已经为我们实现了常用的一些手势识别子类,具体列表如下: 阅读详情

相关推荐

UIGestureRecognizer学习之UIPinchGestureRecognizer(捏合)

UIPinchGestureRecognizer是UIGestureRecognizer的子类。 UIPinchGestureRecognizer除了继承UIGestureRecognizer的属性外,还提供如下俩个属性:scale: //获取捏合的比例 velocity: //获取捏合的速度示例:和前面的UITapGestureRecognizer的例子相似。- (void)viewDidLo

甫式人生 2939

UIPanGestureRecognizer进行视图滑动并处理手势冲突

首先我们肯定是给sourceVC的view上添加平移手势 UIPanGestureRecognizer 手势的实现方法中根据 Pan手势的三种状态 进行sourceVC的view的origin的处理 首先介绍一下 几个方法: 由于我们的sourceVC上存在tableview, 所以会导致tableview的滑动和pan滑动的 手势冲突 , 这也是为什么在上滑动过程中我屏蔽掉了tableview的scrollEnabled。但是当我们sourceVC滑动到上边界后,我们解开了tableview的滑动

Rey的技术博客 1505

C# WPF多页面间的数据共享(经典)

实现页面间的数据共享有很多方法,比如:①事件的发布订阅 ②委托③ioc容器④静态类等,这节主要通过静态的集合实现数据的添加和获取。

sf315418的博客 639

iOS手势篇(五)-UIPanGestureRecognizer详解

UIPanGestureRecognizer是iOS开发中不怎么常用的一个拖动(拖拽)手势. 打开UIPanGestureRecognizer.h头文件 /// 属性 @property (nonatomic) NSUInteger minimumNumberOfTouches __TVOS_PROHIBITED; // default is 1. the minimum n...

MeteoriteMan的博客 1万+

手把手用瑞萨E1仿真器调试RH850 CAN通信:从报文收发到底层寄存器监控

本文详细介绍了使用瑞萨E1仿真器调试RH850 CAN通信的全过程,包括硬件连接、CS+开发环境配置、CAN控制器寄存器解析以及双通道网关实战开发。通过实战案例和错误诊断技巧,帮助开发者快速掌握RH850F1L的RS-CAN控制器应用,提升车载网络开发效率。

weixin_30919429的博客 164

【深度避坑】Word 提示“内存或磁盘空间不足,保存失败”的真正原因与终极解决方案

这是 Word 2003 时代的老功能⚠现代 Office 使用全新的保存 API(与 OneDrive 深度集成)老插件无法兼容现代保存机制会拦截 Word 的写入流程导致保存动作失败,Word 误以为磁盘坏了,于是报错不是磁盘坏了,是 Word 被插件绊倒了。Word 无法保存 = 加载项冲突(尤其是书法 / 稿纸向导)。永久禁用即可彻底恢复。如果在写毕业论文、要交文档,强烈建议马上检查一下你的加载项,避免后期出现大规模崩溃丢稿。

m0_59029415的博客 3082

iOS手势UIGestureRecognizer识别的详细使用(拖动,缩放,旋转,点击,手势依赖,自定义手势) (转)...

1、UIGestureRecognizer介绍 手势识别在iOS上非常重要,手势操作移动设备的重要特征,极大的增加了移动设备使用便捷性。 iOS系统在3.2以后,为方便开发这使用一些常用的手势,提供了UIGestureRecognizer类。手势识别UIGestureRecognizer类是个抽象类,下面的子类是具体的手势,开发这可以直接使用这些手势识别。 UITapG...

dnn77855的博客 200

Windows系统下AutoDock 4.2.6安装避坑指南(附MGLTools配置技巧)

本文详细介绍了在Windows系统下安装和配置AutoDock 4.2.6的完整流程,特别针对分子对接研究中常见的软件安装问题提供了解决方案。从环境准备、分步安装到常见报错处理,涵盖MGLTools配置技巧、工作目录设置和环境变量优化,帮助科研人员快速搭建稳定的分子对接平台。

weixin_29234239的博客 313

vue-fabric-editor移动端手势支持:实现缩放、旋转等触摸操作

在移动设备上使用vue-fabric-editor时,用户常常面临无法通过触摸手势精确操作画布元素的问题。默认情况下,该编辑器主要针对桌面端设计,依赖鼠标和键盘输入。本文将介绍如何为vue-fabric-editor添加移动端手势支持,实现缩放、旋转等常用触摸操作,提升移动用户体验。 ## 二、核心插件与实现原理 vue-fabric-editor采用插件化架构,所有交互功能都通过插件实现。要添...

gitblog_00487的博客 838

从零开始:小鼠Bulk RNA-seq全流程实战指南

本文提供了一份详尽的小鼠Bulk RNA-seq全流程实战指南,涵盖从软件环境搭建、原始数据质控与清洗、序列比对、基因定量到下游差异表达分析与功能富集。内容面向生物信息学新手,通过清晰的代码示例和步骤解析,帮助读者系统掌握Bulk RNA-seq数据分析的核心技能,并产出可靠的生物学洞见。

lake5的博客 721

STM32-DAC定时器触发三角波生成【频率与幅度精准控制】

本文详细介绍了STM32 DAC定时器触发三角波生成的原理与实现方法,涵盖硬件配置、频率与幅度精准控制技巧及代码实现。通过定时器触发DAC模块,可灵活调节三角波的频率和幅度,适用于信号发生器等高精度应用场景。

weixin_29161785的博客 455

【亲测免费】 Moveable: 重新定义Web上的可拖动与可缩放交互体验

Moveable: 重新定义Web上的可拖动与可缩放交互体验 【免费下载链接】moveable Moveable! Draggable! Resizable! Scalable! Rotatable! Warpable! Pinchable! Groupable! Snappable! ...

gitblog_00032的博客 1092

自定义载板RK3588HDMI输入配置完整解决方案

✅ HDMI输入信号检测✅ 自动时序识别(支持1080p@60Hz等标准格式)✅ V4L2视频设备接口✅ 实时视频流捕获✅ H.264编码录制✅ HDCP内容保护支持问题根因识别:发现了hdmim1模块资源冲突的本质问题硬件设计理解:明确了Orange Pi 5 Plus的真实硬件设计意图功能实现:成功启用HDMI输入功能,替代了无法使用的HDMI1输出完整验证:建立了从硬件检测到视频录制的完整测试流程。

梁俊星的博客 1273

IOS 5手势识别教程:二指拨动、拖移以及更多手势

OS 5手势识别教程:二指拨动、拖移以及更多手势   Made in iTyran,Powered By Benna, review by iven、子龙山人。     如果在你的应用程序中需要检测手势,比如点击(tap)、二指拨动 (pinch)、拖移(pan)和旋转(rotation),那么通过创建UIGestureRecogn

万里独行 2097

huggingface下载提示huggingface_hub.errors.EntryNotFoundError:404 Client Error: (Request 1D: Root...如何解决?

🏆 本文收录于《全栈Bug调优(实战版)》专栏,致力于分享我在项目实战过程中遇到的各类Bug及其原因,并提供切实有效的解决方案。无论你是初学者还是经验丰富的开发者,本文将为你指引出一条更高效的Bug修复之路,助你早日登顶,迈向财富自由的梦想🚀!同时,欢迎大家关注、收藏、订阅本专栏,更多精彩内容正在持续更新中。让我们一起进步,Up!Up!Up!    备注: 部分问题/难题源自互联网,经过精心筛选和整理,结合数位十多年大厂实战经验资深大佬经验总结所得,数条可行方案供所需之人参考。

**My Coding Family** 1234

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

OpenLayers移动端地图手势交互完全指南:滑动缩放旋转完美实现方案

OpenLayers是一款功能强大的开源地图库,专门用于在Web应用中显示交互式地图。在移动端开发中,OpenLayers提供了丰富的手势交互功能,包括单指滑动、双指缩放和双指旋转等操作。本文将为您详细解析如何在移动端实现地图手势的完美交互体验。 ## 为什么移动端地图需要专门的手势处理? 在移动设备上,用户习惯使用触摸手势来操作地图:**单指拖动平移**、**双指捏合缩放**、**双指旋转调

gitblog_00687的博客 455

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

【稀缺技术曝光】:.NET MAUI中自定义复合手势识别的实现路径

掌握.NET MAUI中自定义复合手势识别的实现方法,解决复杂交互需求。结合手势识别命令,适用于多点触控、组合滑动等场景,提升应用体验。支持跨平台高效响应,代码灵活易扩展,值得收藏。

LogicNest的博客 442

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

探索 Hammer.js:打造响应式触控体验的终极手势识别库

Hammer.js 是一个功能强大的 JavaScript 手势识别库,让开发者能够轻松为网页添加触摸和鼠标手势支持。无论是滑动、缩放、旋转还是点击,Hammer.js 都能提供精准的手势检测,帮助你构建流畅的交互式 Web 应用。 ## 🌟 为什么选择 Hammer.js? 在移动设备普及的今天,用户期待网页能像原生应用一样响应用户手势。Hammer.js 解决了跨浏览器手势识别的复杂性,

gitblog_00015的博客 655

从零实现3D旋转与缩放,Python视角控制实战案例详解

掌握Python 3D视角控制的核心技巧,从零实现3D模型的旋转与缩放。适用于游戏开发、数据可视化等场景,基于Matplotlib和NumPy实现实时交互控制,代码简洁易懂。提升三维交互体验,值得收藏。

DeepLens的博客 749

彻底解决React Native手势冲突:从多点触控到复杂交互的实战指南

你是否还在为React Native应用中的手势冲突问题头疼?滑动列表时误触按钮、双指缩放与单指拖动互相干扰、自定义手势无法优先响应——这些问题不仅影响用户体验,更可能让精心设计的交互功能无法正常使用。本文将通过create-react-native-app框架,提供一套系统化的手势处理方案,从基础识别到高级冲突解决,帮你构建丝滑的触摸交互体验。 ## 核心依赖与项目初始化 create-re...

gitblog_00706的博客 1063

.NET MAUI中实现自定义手势命令的秘诀(90%开发者忽略的关键细节)

掌握.NET MAUI手势识别命令的实现技巧,解决跨平台交互难题。涵盖自定义手势命令的创建、绑定与优化,适用于移动端复杂操作场景,提升用户体验。关键细节解析助力开发高效响应式应用,值得收藏。

VarLens的博客 325

Hammer.js深度解析:打造Web端丝滑多手势交互体验的终极指南

你是否还在为Web应用中的触摸操作卡顿而烦恼?是否想让按钮点击、图片缩放、页面滑动等交互如原生应用般流畅?Hammer.js作为一款轻量级JavaScript手势库,通过15KB核心体积实现了12种以上手势识别,已成为3000+开源项目的交互解决方案。本文将从实际应用场景出发,带你掌握从基础集成到高级定制的全流程,让普通网页秒变专业级交互界面。 ## 核心价值:为什么选择Hammer.js? ...

gitblog_00482的博客 765

你真的懂手势识别吗?JS实现中的8大坑及避坑指南

掌握JS手势识别实现的正确姿势,避开开发中的常见陷阱。涵盖移动端交互、多点触控处理等场景,详解事件监听、阈值设定等核心方法,提升响应精度与用户体验。8大坑全解析,值得收藏。

FastCompile的博客 353

Hammer.js在Vue项目中的应用:提升移动端用户体验的最佳实践

你是否还在为Vue移动端项目中的手势交互效果不佳而烦恼?滑动不流畅、双击无响应、缩放卡顿等问题不仅影响用户体验,更可能导致用户流失。本文将带你一步步实现Hammer.js与Vue的完美结合,通过具体案例和最佳实践,让你的移动端应用手势交互如丝般顺滑。读完本文,你将掌握: - Hammer.js核心手势识别原理 - Vue项目中Hammer.js的两种集成方式 - 常见手势(点击、滑动、缩放)的实...

gitblog_00610的博客 752

Hammer.js vs 原生触摸API:谁才是前端手势交互的终极选择?

在移动优先的Web开发时代,**Hammer.js** 作为一款专业的JavaScript手势识别库,为开发者提供了强大的多触点手势支持。面对复杂的触摸交互需求,很多开发者都在纠结:是选择成熟的Hammer.js库,还是使用原生的触摸API?今天我们就来深入对比这两者,帮你找到最适合的手势交互解决方案!✨ ## 🤔 什么是Hammer.js手势库? **Hammer.js** 是一个轻量级的

gitblog_00751的博客 1118

Framework7手势库对比:Hammer.js与内置手势系统

你是否还在为移动端应用的手势交互实现而烦恼?既要保证流畅的用户体验,又要兼容不同设备,选择合适的手势库至关重要。本文将深入对比Framework7内置手势系统与Hammer.js,帮助你快速掌握两者的优缺点及适用场景,读完你将能够根据项目需求做出明智选择。 ## 核心功能对比 Framework7作为专注于iOS和Android应用开发的HTML框架,其内置手势系统与组件深度整合,而Hamme...

gitblog_00006的博客 446
上一篇: CATransform3D 矩阵变换之立方体旋转实现细节
下一篇: Redesign Your App for iOS 7 之 页面布局
celljay
博客等级 码龄15年 1粉丝 7原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值