text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```objective-c // // YFWaterWaveViewController.m // BigShow1949 // // Created by zhht01 on 16/1/20. // #import "YFWaterWaveViewController.h" @interface YFWaterWaveViewController () @end @implementation YFWaterWaveViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupDataArr:@[@[@"",@"YFRippleViewController"], @[@"2",@"YFRipple2ViewController"], @[@"",@"YFOneWaterWaveViewController"], @[@"",@"YFTwoWaterWaveViewController"], @[@"",@"YFWaterRippleViewController"],]]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/YFWaterWaveViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
133
```objective-c // // YFWaterWaveViewController.h // BigShow1949 // // Created by zhht01 on 16/1/20. // #import "BaseTableViewController.h" @interface YFWaterWaveViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/YFWaterWaveViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
55
```objective-c // // YFRippleViewController.h // BigShow1949 // // Created by zhht01 on 16/1/20. // #import <UIKit/UIKit.h> @interface YFRippleViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/01 - 放大水波纹/YFRippleViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // XXBRippleView.h // waterTest // // Created by Jinhong on 15/2/5. // #import <UIKit/UIKit.h> @interface XXBRippleView : UIView /** * 20 */ @property(nonatomic , assign)CGFloat minRadius; /** * 50 */ @property(nonatomic , assign)CGFloat maxRadius; /** * */ @property(nonatomic , strong)UIColor *rippleColor; /** * 1 */ @property(nonatomic , assign)CGFloat rippleWidth; /** * */ @property(nonatomic , assign)CGFloat animationTime; /** * */ - (void)startRippleAnimation; /** * */ - (void)startRippleAnimationOnce; /** * */ - (void)stopRippleAnimation; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/01 - 放大水波纹/XXBRippleView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
168
```objective-c // // YFRippleViewController.m // BigShow1949 // // Created by zhht01 on 16/1/20. // #import "YFRippleViewController.h" #import "XXBRippleView.h" @interface YFRippleViewController () //@property (weak, nonatomic) IBOutlet XXBRippleView *rippleView; @property (nonatomic, strong) XXBRippleView *rippleView; @end @implementation YFRippleViewController - (void)viewDidLoad { self.view.backgroundColor = [UIColor whiteColor]; // UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake(50, 100, 100, 40)]; // [startBtn setTitle:@"" forState:UIControlStateNormal]; // [startBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; // [startBtn addTarget:self action:@selector(start) forControlEvents:UIControlEventTouchUpInside]; // [self.view addSubview:startBtn]; // // UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(200, 100, 100, 40)]; // [endBtn setTitle:@"" forState:UIControlStateNormal]; // [endBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; // [startBtn addTarget:self action:@selector(end) forControlEvents:UIControlEventTouchUpInside]; // [self.view addSubview:endBtn]; XXBRippleView *rippleView = [[XXBRippleView alloc] initWithFrame:CGRectMake(100, 200, 200, 200)]; self.rippleView = rippleView; [self.view addSubview:self.rippleView]; [self.rippleView startRippleAnimation]; } - (void)start { [self.rippleView startRippleAnimation]; } - (void)end { [self.rippleView stopRippleAnimation]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/01 - 放大水波纹/YFRippleViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
359
```objective-c // // XXBRippleView.m // waterTest // // Created by Jinhong on 15/2/5. // #import "XXBRippleView.h" @interface XXBRippleView () /** * */ @property(nonatomic , assign)NSInteger radiuNumber; /** * */ @property(nonatomic , strong)NSTimer *animationTimer; /** * */ @property(nonatomic , assign)CGFloat pantographProportion; @end @implementation XXBRippleView - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { [self setupRippleView]; } return self; } - (id)initWithCoder:(NSCoder *)aDecoder { if (self = [super initWithCoder:aDecoder]) { [self setupRippleView]; } return self; } - (void)setupRippleView { self.backgroundColor = [UIColor clearColor]; self.userInteractionEnabled = NO; } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self startRippleAnimation]; } /** * */ - (void)startRippleAnimation { /** * */ if (self.animationTimer) return; NSTimer *animationTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(rippleAnimation) userInfo:nil repeats:YES]; self.animationTimer = animationTimer; /** * timer */ [[NSRunLoop currentRunLoop] addTimer:animationTimer forMode:NSRunLoopCommonModes]; } /** * */ - (void)startRippleAnimationOnce { [self rippleAnimation]; } /** * */ - (void)stopRippleAnimation { [self.animationTimer invalidate]; self.animationTimer = nil; } /** * */ - (void)rippleAnimation { UIColor *stroke = self.rippleColor; CGRect pathFrame = CGRectMake(-self.minRadius, -self.minRadius,self.minRadius * 2,self.minRadius * 2); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathFrame cornerRadius:self.minRadius ]; CGPoint shapePosition = [self convertPoint:self.center fromView:nil]; CAShapeLayer *circleShape = [CAShapeLayer layer]; circleShape.path = path.CGPath; circleShape.position = shapePosition; circleShape.fillColor = [UIColor clearColor].CGColor; circleShape.opacity = 0; circleShape.strokeColor = stroke.CGColor; circleShape.lineWidth = self.rippleWidth; [self.layer addSublayer:circleShape]; CAKeyframeAnimation *scaleAnimation = [CAKeyframeAnimation animation]; scaleAnimation.keyPath = @"transform.scale"; NSMutableArray *valueArray = [NSMutableArray array]; for(int i = 0 ; i<6 ; i++) { CGFloat percent = i/6.0 * self.pantographProportion; NSValue *value = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0 + percent ,1.0 + percent, 1)]; [valueArray addObject:value]; } scaleAnimation.values = valueArray; // scaleAnimation.keyTimes = @[@(0.1),@(0.4),@(0.65),@(0.85),@(0.95),@(1.0)]; CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; alphaAnimation.fromValue = @1; alphaAnimation.toValue = @0; CAAnimationGroup *animation = [CAAnimationGroup animation]; animation.animations = @[scaleAnimation, alphaAnimation]; /** * */ animation.duration = self.animationTime; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [circleShape addAnimation:animation forKey:nil]; } - (UIColor *)rippleColor { if (_rippleColor == nil) { _rippleColor = [UIColor grayColor]; } return _rippleColor; } - (CGFloat)minRadius { if(_minRadius <= 0) { _minRadius = 20.0; } return _minRadius; } - (CGFloat)maxRadius { if (_maxRadius <= 0) { _maxRadius = 150.0; } return _maxRadius; } - (CGFloat)pantographProportion { if (_pantographProportion <=0) { _pantographProportion = self.maxRadius/self.minRadius - 1.0; } return _pantographProportion; } - (CGFloat)rippleWidth { if (_rippleWidth <= 0) { _rippleWidth = 1.0; } return _rippleWidth; } - (CGFloat)animationTime { if (_animationTime <= 0 ) { _animationTime = 2.0; } return _animationTime; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/01 - 放大水波纹/XXBRippleView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,083
```objective-c // // LXHTwoWaterWaveController.m // // // Created by on 15/12/22. // #import "LXHTwoWaterWaveView.h" @interface LXHTwoWaterWaveView () { UIColor *_waterColor1; UIColor *_waterColor2; float _currentLinePointY1; float _currentLinePointY2; float a; float b; BOOL flag; } @end @implementation LXHTwoWaterWaveView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self setBackgroundColor:[UIColor clearColor]]; a = 1.5; b = 0; flag = NO; _waterColor1 = [UIColor redColor]; _waterColor2 = [UIColor orangeColor]; _currentLinePointY1 = 330; _currentLinePointY2 = 340; [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(animateWave) userInfo:nil repeats:YES]; } return self; } -(void)animateWave { if (flag) { a += 0.01; }else{ a -= 0.01; } if (a <= 1) { flag = YES; } if (a >= 1.5) { flag = NO; } b += 0.1; [self setNeedsDisplay]; } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // CGContextRef context1 = UIGraphicsGetCurrentContext(); CGMutablePathRef path1 = CGPathCreateMutable(); // CGContextSetLineWidth(context1, 5); CGContextSetFillColorWithColor(context1, [_waterColor1 CGColor]); // CGContextSetStrokeColorWithColor(context1, [[UIColor blueColor] CGColor]); float y1 = _currentLinePointY1; CGPathMoveToPoint(path1, NULL, 0, y1); for(float x = 0;x <= self.bounds.size.width;x++){ y1 = a * sin( x / 180 * M_PI + 4 * b / M_PI ) * 5 + _currentLinePointY1; CGPathAddLineToPoint(path1, nil, x, y1); } CGContextAddPath(context1, path1); // CGContextStrokePath(context1); CGPathAddLineToPoint(path1, nil, self.bounds.size.width, rect.size.height); CGPathAddLineToPoint(path1, nil, 0, rect.size.height); CGPathAddLineToPoint(path1, nil, 0, _currentLinePointY1); CGContextAddPath(context1, path1); CGContextFillPath(context1); CGPathRelease(path1); // CGContextRef context2 = UIGraphicsGetCurrentContext(); CGMutablePathRef path2 = CGPathCreateMutable(); // CGContextSetLineWidth(context1, 1); CGContextSetFillColorWithColor(context2, [_waterColor2 CGColor]); float y2 = _currentLinePointY2; CGPathMoveToPoint(path2, NULL, 0, y2); for(float x = 0;x <= self.bounds.size.width;x++){ y2 = a * cos(x / 180 * M_PI + 4 * b / M_PI ) * 5 + _currentLinePointY2; CGPathAddLineToPoint(path2, nil, x, y2); } CGContextAddPath(context2, path2); CGPathAddLineToPoint(path2, nil, self.bounds.size.width, rect.size.height); CGPathAddLineToPoint(path2, nil, 0, rect.size.height); CGPathAddLineToPoint(path2, nil, 0, _currentLinePointY2); CGContextAddPath(context2, path2); CGContextFillPath(context2); CGPathRelease(path2); } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/04 - 两条水纹/LXHTwoWaterWaveView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
888
```objective-c // // LXHTwoWaterWaveController.h // // // Created by on 15/12/22. // #import <UIKit/UIKit.h> @interface LXHTwoWaterWaveView : UIView @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/04 - 两条水纹/LXHTwoWaterWaveView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
47
```objective-c // // YFTwoWaterWaveViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFTwoWaterWaveViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/04 - 两条水纹/YFTwoWaterWaveViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
54
```objective-c // // YFTwoWaterWaveViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFTwoWaterWaveViewController.h" #import "LXHTwoWaterWaveView.h" @interface YFTwoWaterWaveViewController () @end @implementation YFTwoWaterWaveViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; LXHTwoWaterWaveView *waterView = [[LXHTwoWaterWaveView alloc]initWithFrame:self.view.bounds]; [self.view addSubview:waterView]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/04 - 两条水纹/YFTwoWaterWaveViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
133
```objective-c // // YFWaterRipple2ViewController.h // appStoreDemo // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> #import "RippleTableViewController.h" #import "GLIRViewController.h" @interface YFWaterRipple2ViewController : RippleTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/YFWaterRipple2ViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
72
```glsl uniform sampler2D SamplerRGB; varying highp vec2 texCoordVarying; void main() { gl_FragColor = texture2D(SamplerRGB, texCoordVarying); } ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/Shader.fsh
glsl
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
44
```glsl attribute vec4 position; attribute vec2 texCoord; varying vec2 texCoordVarying; void main() { gl_Position = position; texCoordVarying = texCoord; } ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/Shader.vsh
glsl
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
43
```objective-c // // GLIRViewController.h // // Modified by Denis Berton // // GLIRViewController is based on gl_image_ripple (path_to_url // // Created by Daniel Stepp on 9/1/12. // #import <GLKit/GLKit.h> //#import "RippleModel2.h" @interface GLIRViewController : GLKViewController { // RippleModel2 *_ripple; CADisplayLink* displayLink; BOOL stopUdpate; } @property (nonatomic, strong) NSString * rippleImageName; - (void)render:(CADisplayLink*)displayLink; - (void)cleanRipple; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/GLIRViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
139
```objective-c // // YFWaterRipple2ViewController.m // appStoreDemo // // Created by zhht01 on 16/1/21. // #import "YFWaterRipple2ViewController.h" @interface YFWaterRipple2ViewController () { NSMutableArray * _objects; } @end @implementation YFWaterRipple2ViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { self.rippleImageName = @"back.jpg"; [super viewDidLoad]; self.navigationController.navigationBarHidden = YES; [self randomValues]; [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"ID"]; } #pragma mark - random datasource's values - (void)randomValues { _objects = [[NSMutableArray alloc]init]; for (NSUInteger i = 0; i < 50; ++i) { [_objects addObject:[NSNumber numberWithInteger:i]]; } } #pragma mark - Table View - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _objects.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString * strID = @"ID"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strID forIndexPath:indexPath]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strID]; } cell.selectionStyle = UITableViewCellSelectionStyleNone; cell.backgroundColor = [UIColor clearColor]; NSNumber *number = _objects[indexPath.row]; cell.textLabel.text = [number stringValue]; cell.textLabel.textColor = [UIColor whiteColor]; return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/YFWaterRipple2ViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
441
```objective-c /* File: RippleModel22.h Abstract: Ripple model class that simulates the ripple effect. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <Foundation/Foundation.h> #import <OpenGLES/ES2/gl.h> @interface RippleModel2 : NSObject - (GLfloat *)getVertices; - (GLfloat *)getTexCoords; - (GLushort *)getIndices; - (unsigned int)getVertexSize; - (unsigned int)getIndexSize; - (unsigned int)getIndexCount; - (id)initWithScreenWidth:(unsigned int)width screenHeight:(unsigned int)height meshFactor:(unsigned int)factor touchRadius:(unsigned int)radius textureWidth:(unsigned int)texWidth textureHeight:(unsigned int)texHeight; - (void)runSimulation; - (void)initiateRippleAtLocation:(CGPoint)location; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/RippleModel2.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
644
```objective-c // // RippleTableViewController.m // RippleTableViewController // // Created by Denis Berton // #import "RippleTableViewController.h" @interface RippleTableViewController ()<UIGestureRecognizerDelegate> @end @implementation RippleTableViewController - (void)viewDidLoad { [super viewDidLoad]; self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds]; self.tableView.dataSource = self; self.tableView.delegate = self; self.tableView.autoresizesSubviews = YES; self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight; self.tableView.backgroundColor = [UIColor clearColor]; [self.view addSubview:self.tableView]; self.view.backgroundColor = [UIColor clearColor]; UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; panGestureRecognizer.enabled = YES; panGestureRecognizer.cancelsTouchesInView = NO; panGestureRecognizer.delegate = self; [self.tableView addGestureRecognizer:panGestureRecognizer]; UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)]; singleTapGestureRecognizer.numberOfTapsRequired = 1; singleTapGestureRecognizer.enabled = YES; singleTapGestureRecognizer.cancelsTouchesInView = NO; singleTapGestureRecognizer.delegate = self; [self.tableView addGestureRecognizer:singleTapGestureRecognizer]; } -(void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // [self cleanRipple]; stopUdpate = NO; } -(void) viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; stopUdpate = YES; // [self cleanRipple]; } - (void)handlePanGesture:(UITapGestureRecognizer *)gesture { CGPoint location = [gesture locationInView:nil]; // [_ripple initiateRippleAtLocation:location]; } #pragma mark - UIGestureRecognizerDelegate - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } #pragma mark - UITableViewDelegate - (void)scrollViewDidScroll:(UIScrollView *)scrollView { //avoid UIKit freeze [self render:displayLink]; } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 0; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { return nil; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/RippleTableViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
507
```objective-c // // GLIRViewController.m // // Modified by Denis Berton // // GLIRViewController is based on gl_image_ripple (path_to_url // // Created by Daniel Stepp on 9/1/12. // #import <CoreVideo/CVOpenGLESTextureCache.h> #import <QuartzCore/QuartzCore.h> #include <stdlib.h> #import "GLIRViewController.h" // Uniform index. enum { UNIFORM_Y, UNIFORM_UV, UNIFORM_RGB, NUM_UNIFORMS }; GLint uniforms[NUM_UNIFORMS]; // Attribute index. enum { ATTRIB_VERTEX, ATTRIB_TEXCOORD, ATTRIB_COLOR, NUM_ATTRIBUTES }; @interface GLIRViewController (){ CGFloat _screenWidth; CGFloat _screenHeight; unsigned int _meshFactor; GLuint _program; CVImageBufferRef _pixelBuffer; size_t _width; size_t _height; CVOpenGLESTextureCacheRef _textureCache; CVOpenGLESTextureRef _texture; GLuint _positionVBO; GLuint _texcoordVBO; GLuint _indexVBO; EAGLContext *_context; } @property (strong, nonatomic) EAGLContext *context; - (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle; @end @implementation GLIRViewController @synthesize context = _context; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle { CGFloat angleInRadians = angle * (M_PI / 180); CGFloat width = CGImageGetWidth(imgRef); CGFloat height = CGImageGetHeight(imgRef); CGRect imgRect = CGRectMake(0, 0, width, height); CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians); CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bmContext = CGBitmapContextCreate(NULL, rotatedRect.size.width, rotatedRect.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextSetAllowsAntialiasing(bmContext, YES); CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh); CGColorSpaceRelease(colorSpace); CGContextTranslateCTM(bmContext, +(rotatedRect.size.width/2), +(rotatedRect.size.height/2)); CGContextRotateCTM(bmContext, angleInRadians); CGContextDrawImage(bmContext, CGRectMake(-width/2, -height/2, width, height), imgRef); CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext); CFRelease(bmContext); return rotatedImage; } - (void)viewDidLoad { [super viewDidLoad]; stopUdpate = NO; self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; if (!self.context) { NSLog(@"Failed to create ES context"); } GLKView *view = (GLKView *)self.view; view.context = self.context; // self.preferredFramesPerSecond = 60; //avoid UIKit freeze //path_to_url view.enableSetNeedsDisplay = NO; self.preferredFramesPerSecond = 0; displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render:)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; displayLink.frameInterval = 2; _screenWidth = [UIScreen mainScreen].bounds.size.width; _screenHeight = [UIScreen mainScreen].bounds.size.height; view.contentScaleFactor = [UIScreen mainScreen].scale; if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { // meshFactor controls the ending ripple mesh size. // For example mesh width = screenWidth / meshFactor. // It's chosen based on both screen resolution and device size. _meshFactor = 8; } else { _meshFactor = 4; } [self setupGL]; UIImage * myImage = [UIImage imageNamed:self.rippleImageName]; CGImageRef imageRef = [myImage CGImage]; imageRef = [self CGImageRotatedByAngle:imageRef angle:90.0f]; _pixelBuffer = [self pixelBufferFromCGImage:imageRef]; _width = CVPixelBufferGetWidth(_pixelBuffer); _height = CVPixelBufferGetHeight(_pixelBuffer); //-- Create CVOpenGLESTextureCacheRef for optimal CVImageBufferRef to GLES texture conversion. CVReturn err = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, (__bridge CVEAGLContext)((__bridge void *)_context), NULL, &_textureCache); if (err) { NSLog(@"Error at CVOpenGLESTextureCacheCreate %d", err); return; } } - (void)render:(CADisplayLink*)displayLink { GLKView* view = (GLKView*)self.view; //avoid UIKit freeze [self update]; [view display]; } - (void)cleanUpTextures { if (_texture) { CFRelease(_texture); _texture = NULL; } CVOpenGLESTextureCacheFlush(_textureCache, 0); } - (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image { CGSize frameSize = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image)); NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO], kCVPixelBufferCGImageCompatibilityKey, [NSNumber numberWithBool:NO], kCVPixelBufferCGBitmapContextCompatibilityKey, nil]; CVPixelBufferRef pxbuffer = NULL; CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, frameSize.width, frameSize.height, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef) options, &pxbuffer); NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL); CVPixelBufferLockBaseAddress(pxbuffer, 0); void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer); CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pxdata, frameSize.width, frameSize.height, 8, 4*frameSize.width, rgbColorSpace, kCGImageAlphaPremultipliedFirst); CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); CGColorSpaceRelease(rgbColorSpace); CGContextRelease(context); CVPixelBufferUnlockBaseAddress(pxbuffer, 0); return pxbuffer; } - (void)setupGL { [EAGLContext setCurrentContext:self.context]; [self loadShaders]; glUseProgram(_program); glUniform1i(uniforms[UNIFORM_RGB], 0); } - (void)setupBuffers { // glGenBuffers(1, &_indexVBO); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexVBO); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, [_ripple getIndexSize], [_ripple getIndices], GL_STATIC_DRAW); // // glGenBuffers(1, &_positionVBO); // glBindBuffer(GL_ARRAY_BUFFER, _positionVBO); // glBufferData(GL_ARRAY_BUFFER, [_ripple getVertexSize], [_ripple getVertices], GL_STATIC_DRAW); // // glEnableVertexAttribArray(ATTRIB_VERTEX); // glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, 2*sizeof(GLfloat), 0); // // glGenBuffers(1, &_texcoordVBO); // glBindBuffer(GL_ARRAY_BUFFER, _texcoordVBO); // glBufferData(GL_ARRAY_BUFFER, [_ripple getVertexSize], [_ripple getTexCoords], GL_DYNAMIC_DRAW); // // glEnableVertexAttribArray(ATTRIB_TEXCOORD); // glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 2*sizeof(GLfloat), 0); } - (void)tearDownGL { [EAGLContext setCurrentContext:_context]; glDeleteBuffers(1, &_positionVBO); glDeleteBuffers(1, &_texcoordVBO); glDeleteBuffers(1, &_indexVBO); if (_program) { glDeleteProgram(_program); _program = 0; } } - (void)viewDidUnload { [super viewDidUnload]; [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } self.context = nil; [displayLink invalidate]; displayLink = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } #pragma mark - GLKViewDelegate - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { glClear(GL_COLOR_BUFFER_BIT); // if (_ripple) // { // unsigned int indexCount = [_ripple getIndexCount]; // glDrawElements(GL_TRIANGLE_STRIP, indexCount, GL_UNSIGNED_SHORT, 0); // } } #pragma mark - GLKViewControllerDelegate - (void)update { if(stopUdpate) { return; } if (!_textureCache) { NSLog(@"No video texture cache"); return; } // if (!_ripple) // { // [self loadImageIntoPond:self.rippleImageName]; // } // // if (_ripple) // { // [_ripple runSimulation]; // // // no need to rebind GL_ARRAY_BUFFER to _texcoordVBO since it should be still be bound from setupBuffers // unsigned int vertexSize = [_ripple getVertexSize]; // GLfloat * texCoords = [_ripple getTexCoords]; // glBufferData(GL_ARRAY_BUFFER, vertexSize, texCoords, GL_DYNAMIC_DRAW); // } } -(void)loadImageIntoPond:(NSString *)fileName { [EAGLContext setCurrentContext:_context]; glDeleteBuffers(1, &_positionVBO); glDeleteBuffers(1, &_texcoordVBO); glDeleteBuffers(1, &_indexVBO); // if (_ripple) _ripple = nil; // _ripple = [[RippleModel2 alloc] initWithScreenWidth:_screenWidth // screenHeight:_screenHeight // meshFactor:_meshFactor // touchRadius:5 // textureWidth:_width // textureHeight:_height]; [self setupBuffers]; glActiveTexture(GL_TEXTURE0); // 1 UIImage * image = [UIImage imageNamed:fileName]; CGImageRef spriteImage = image.CGImage; spriteImage = [self CGImageRotatedByAngle:spriteImage angle:90.0f]; if (!spriteImage) { NSLog(@"Failed to load image %@", @"image"); exit(1); } // 2 _width = CGImageGetWidth(spriteImage); _height = CGImageGetHeight(spriteImage); GLubyte * spriteData = (GLubyte *) calloc(_width*_height*4, sizeof(GLubyte)); CGContextRef spriteContext = CGBitmapContextCreate(spriteData, _width, _height, 8, _width*4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast); // 3 CGContextDrawImage(spriteContext, CGRectMake(0, 0, _width, _height), spriteImage); CGContextRelease(spriteContext); // 4 GLuint texName; glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData); free(spriteData); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } #pragma mark - OpenGL ES 2 shader compilation - (BOOL)loadShaders { GLuint vertShader, fragShader; NSString *vertShaderPathname, *fragShaderPathname; // Create shader program. _program = glCreateProgram(); // Create and compile vertex shader. vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"]; if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname]) { NSLog(@"Failed to compile vertex shader"); return NO; } // Create and compile fragment shader. fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"]; if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) { NSLog(@"Failed to compile fragment shader"); return NO; } // Attach vertex shader to program. glAttachShader(_program, vertShader); // Attach fragment shader to program. glAttachShader(_program, fragShader); // Bind attribute locations. // This needs to be done prior to linking. glBindAttribLocation(_program, ATTRIB_VERTEX, "position"); glBindAttribLocation(_program, ATTRIB_TEXCOORD, "texCoord"); // Link program. if (![self linkProgram:_program]) { NSLog(@"Failed to link program: %d", _program); if (vertShader) { glDeleteShader(vertShader); vertShader = 0; } if (fragShader) { glDeleteShader(fragShader); fragShader = 0; } if (_program) { glDeleteProgram(_program); _program = 0; } return NO; } // Get uniform locations. uniforms[UNIFORM_RGB] = glGetUniformLocation(_program, "SamplerRGB"); // Release vertex and fragment shaders. if (vertShader) { glDetachShader(_program, vertShader); glDeleteShader(vertShader); } if (fragShader) { glDetachShader(_program, fragShader); glDeleteShader(fragShader); } return YES; } - (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file { GLint status; const GLchar *source; source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String]; if (!source) { NSLog(@"Failed to load vertex shader"); return NO; } *shader = glCreateShader(type); glShaderSource(*shader, 1, &source, NULL); glCompileShader(*shader); #if defined(DEBUG) GLint logLength; glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetShaderInfoLog(*shader, logLength, &logLength, log); NSLog(@"Shader compile log:\n%s", log); free(log); } #endif glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); if (status == 0) { glDeleteShader(*shader); return NO; } return YES; } - (BOOL)linkProgram:(GLuint)prog { GLint status; glLinkProgram(prog); #if defined(DEBUG) GLint logLength; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program link log:\n%s", log); free(log); } #endif glGetProgramiv(prog, GL_LINK_STATUS, &status); if (status == 0) { return NO; } return YES; } -(void) cleanRipple{ // if(_ripple){ // _ripple = nil; // } } #pragma mark - Touch handling methods - (void)myTouch:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { CGPoint location = [touch locationInView:touch.view]; // [_ripple initiateRippleAtLocation:location]; } } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self myTouch:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self myTouch:touches withEvent:event]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/GLIRViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,804
```objective-c // // RippleTableViewController.h // RippleTableViewController // // Created by Denis Berton // #import <UIKit/UIKit.h> #import "GLIRViewController.h" @interface RippleTableViewController : GLIRViewController <UITableViewDataSource, UITableViewDelegate> @property (nonatomic,strong) UITableView *tableView; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/RippleTableViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
63
```objective-c // // YFWaterRippleViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFWaterRippleViewController.h" #import "RippleModel.h" #import "RippleView.h" @interface YFWaterRippleViewController (){ RippleView *rippleView; } @end @implementation YFWaterRippleViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; UIImage *image = [UIImage imageNamed:@"home_top_bg"]; EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2]; rippleView = [[RippleView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height) context:context]; [self.view addSubview:rippleView]; UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; [rippleView addGestureRecognizer:pan]; UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; [rippleView addGestureRecognizer:tap]; } - (void)handleGesture:(UITapGestureRecognizer *)gesture { CGPoint location = [gesture locationInView:rippleView]; [rippleView.ripple initiateRippleAtLocation:location]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/YFWaterRippleViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
306
```objective-c // // YFWaterRippleViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFWaterRippleViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/YFWaterRippleViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
54
```objective-c /* File: RippleModel22.m Abstract: Ripple model class that simulates the ripple effect. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import "RippleModel2.h" @interface RippleModel2 () { unsigned int screenWidth; unsigned int screenHeight; unsigned int poolWidth; unsigned int poolHeight; unsigned int touchRadius; unsigned int meshFactor; float texCoordFactorS; float texCoordOffsetS; float texCoordFactorT; float texCoordOffsetT; // ripple coefficients float *rippleCoeff; // ripple simulation buffers float *rippleSource; float *rippleDest; // data passed to GL GLfloat *rippleVertices; GLfloat *rippleTexCoords; GLushort *rippleIndicies; } @end @implementation RippleModel2 - (void)initRippleMap { // +2 for padding the border memset(rippleSource, 0, (poolWidth+2)*(poolHeight+2)*sizeof(float)); memset(rippleDest, 0, (poolWidth+2)*(poolHeight+2)*sizeof(float)); } - (void)initRippleCoeff { for (int y=0; y<=2*touchRadius; y++) { for (int x=0; x<=2*touchRadius; x++) { float distance = sqrt((x-touchRadius)*(x-touchRadius)+(y-touchRadius)*(y-touchRadius)); if (distance <= touchRadius) { float factor = (distance/touchRadius); // goes from -512 -> 0 rippleCoeff[y*(touchRadius*2+1)+x] = -(cos(factor*M_PI)+1.f) * 256.f; } else { rippleCoeff[y*(touchRadius*2+1)+x] = 0.f; } } } } - (void)initMesh { unsigned int index1 = 0; unsigned int index2 = 0; for (int i=0; i<poolHeight; i++) { for (int j=0; j<poolWidth; j++) { index1 = (i*poolWidth+j)*2+0; index2 = (i*poolWidth+j)*2+1; rippleVertices[index1] = -1.f + j*(2.f/(poolWidth-1)); rippleVertices[index2] = 1.f - i*(2.f/(poolHeight-1)); rippleTexCoords[index1] = (float)i/(poolHeight-1) * texCoordFactorS + texCoordOffsetS; rippleTexCoords[index2] = (1.f - (float)j/(poolWidth-1)) * texCoordFactorT + texCoordFactorT; } } unsigned int index = 0; for (int i=0; i<poolHeight-1; i++) { for (int j=0; j<poolWidth; j++) { if (i%2 == 0) { // emit extra index to create degenerate triangle if (j == 0) { rippleIndicies[index] = i*poolWidth+j; index++; } rippleIndicies[index] = i*poolWidth+j; index++; rippleIndicies[index] = (i+1)*poolWidth+j; index++; // emit extra index to create degenerate triangle if (j == (poolWidth-1)) { rippleIndicies[index] = (i+1)*poolWidth+j; index++; } } else { // emit extra index to create degenerate triangle if (j == 0) { rippleIndicies[index] = (i+1)*poolWidth+j; index++; } rippleIndicies[index] = (i+1)*poolWidth+j; index++; rippleIndicies[index] = i*poolWidth+j; index++; // emit extra index to create degenerate triangle if (j == (poolWidth-1)) { rippleIndicies[index] = i*poolWidth+j; index++; } } } } } - (GLfloat *)getVertices { return rippleVertices; } - (GLfloat *)getTexCoords { return rippleTexCoords; } - (GLushort *)getIndices { return rippleIndicies; } - (unsigned int)getVertexSize { return poolWidth*poolHeight*2*sizeof(GLfloat); } - (unsigned int)getIndexSize { return (poolHeight-1)*(poolWidth*2+2)*sizeof(GLushort); } - (unsigned int)getIndexCount { return [self getIndexSize]/sizeof(*rippleIndicies); } - (void)freeBuffers { free(rippleCoeff); free(rippleSource); free(rippleDest); free(rippleVertices); free(rippleTexCoords); free(rippleIndicies); } - (id)initWithScreenWidth:(unsigned int)width screenHeight:(unsigned int)height meshFactor:(unsigned int)factor touchRadius:(unsigned int)radius textureWidth:(unsigned int)texWidth textureHeight:(unsigned int)texHeight { self = [super init]; if (self) { screenWidth = width; screenHeight = height; meshFactor = factor; poolWidth = width/meshFactor; poolHeight = height/meshFactor; touchRadius = radius; if ((float)screenHeight/screenWidth < (float)texWidth/texHeight) { texCoordFactorS = (float)(texHeight*screenHeight)/(screenWidth*texWidth); texCoordOffsetS = (1.f - texCoordFactorS)/2.f; texCoordFactorT = 1.f; texCoordOffsetT = 0.f; } else { texCoordFactorS = 1.f; texCoordOffsetS = 0.f; texCoordFactorT = (float)(screenWidth*texWidth)/(texHeight*screenHeight); texCoordOffsetT = (1.f - texCoordFactorT)/2.f; } rippleCoeff = (float *)malloc((touchRadius*2+1)*(touchRadius*2+1)*sizeof(float)); // +2 for padding the border rippleSource = (float *)malloc((poolWidth+2)*(poolHeight+2)*sizeof(float)); rippleDest = (float *)malloc((poolWidth+2)*(poolHeight+2)*sizeof(float)); rippleVertices = (GLfloat *)malloc(poolWidth*poolHeight*2*sizeof(GLfloat)); rippleTexCoords = (GLfloat *)malloc(poolWidth*poolHeight*2*sizeof(GLfloat)); rippleIndicies = (GLushort *)malloc((poolHeight-1)*(poolWidth*2+2)*sizeof(GLushort)); if (!rippleCoeff || !rippleSource || !rippleDest || !rippleVertices || !rippleTexCoords || !rippleIndicies) { [self freeBuffers]; return nil; } [self initRippleMap]; [self initRippleCoeff]; [self initMesh]; } return self; } - (void)runSimulation { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // first pass for simulation buffers... dispatch_apply(poolHeight, queue, ^(size_t y) { for (int x=0; x<poolWidth; x++) { // * - denotes current pixel // // a // c * d // b // +1 to both x/y values because the border is padded float a = rippleSource[(y)*(poolWidth+2) + x+1]; float b = rippleSource[(y+2)*(poolWidth+2) + x+1]; float c = rippleSource[(y+1)*(poolWidth+2) + x]; float d = rippleSource[(y+1)*(poolWidth+2) + x+2]; float result = (a + b + c + d)/2.f - rippleDest[(y+1)*(poolWidth+2) + x+1]; result -= result/32.f; rippleDest[(y+1)*(poolWidth+2) + x+1] = result; } }); // second pass for modifying texture coord dispatch_apply(poolHeight, queue, ^(size_t y) { for (int x=0; x<poolWidth; x++) { // * - denotes current pixel // // a // c * d // b // +1 to both x/y values because the border is padded float a = rippleDest[(y)*(poolWidth+2) + x+1]; float b = rippleDest[(y+2)*(poolWidth+2) + x+1]; float c = rippleDest[(y+1)*(poolWidth+2) + x]; float d = rippleDest[(y+1)*(poolWidth+2) + x+2]; float s_offset = ((b - a) / 2048.f); float t_offset = ((c - d) / 2048.f); // clamp s_offset = (s_offset < -0.5f) ? -0.5f : s_offset; t_offset = (t_offset < -0.5f) ? -0.5f : t_offset; s_offset = (s_offset > 0.5f) ? 0.5f : s_offset; t_offset = (t_offset > 0.5f) ? 0.5f : t_offset; float s_tc = (float)y/(poolHeight-1) * texCoordFactorS + texCoordOffsetS; float t_tc = (1.f - (float)x/(poolWidth-1)) * texCoordFactorT + texCoordOffsetT; rippleTexCoords[(y*poolWidth+x)*2+0] = s_tc + s_offset; rippleTexCoords[(y*poolWidth+x)*2+1] = t_tc + t_offset; } }); float *pTmp = rippleDest; rippleDest = rippleSource; rippleSource = pTmp; } - (void)initiateRippleAtLocation:(CGPoint)location { unsigned int xIndex = (unsigned int)((location.x / screenWidth) * poolWidth); unsigned int yIndex = (unsigned int)((location.y / screenHeight) * poolHeight); for (int y=(int)yIndex-(int)touchRadius; y<=(int)yIndex+(int)touchRadius; y++) { for (int x=(int)xIndex-(int)touchRadius; x<=(int)xIndex+(int)touchRadius; x++) { if (x>=0 && x<poolWidth && y>=0 && y<poolHeight) { // +1 to both x/y values because the border is padded rippleSource[(poolWidth+2)*(y+1)+x+1] += rippleCoeff[(y-(yIndex-touchRadius))*(touchRadius*2+1)+x-(xIndex-touchRadius)]; } } } } - (void)dealloc { [self freeBuffers]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/06 - 水波纹2/RippleTableViewController/RippleModel2.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,952
```objective-c /* File: RippleModel.m Abstract: Ripple model class that simulates the ripple effect. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import "RippleModel.h" @interface RippleModel () { unsigned int screenWidth; unsigned int screenHeight; unsigned int poolWidth; unsigned int poolHeight; unsigned int touchRadius; unsigned int meshFactor; float texCoordFactorS; float texCoordOffsetS; float texCoordFactorT; float texCoordOffsetT; // ripple coefficients float *rippleCoeff; // ripple simulation buffers float *rippleSource; float *rippleDest; // data passed to GL GLfloat *rippleVertices; GLfloat *rippleTexCoords; GLushort *rippleIndicies; } @end @implementation RippleModel - (void)initRippleMap { // +2 for padding the border memset(rippleSource, 0, (poolWidth+2)*(poolHeight+2)*sizeof(float)); memset(rippleDest, 0, (poolWidth+2)*(poolHeight+2)*sizeof(float)); } - (void)initRippleCoeff { for (int y=0; y<=2*touchRadius; y++) { for (int x=0; x<=2*touchRadius; x++) { float distance = sqrt((x-touchRadius)*(x-touchRadius)+(y-touchRadius)*(y-touchRadius)); if (distance <= touchRadius) { float factor = (distance/touchRadius); // goes from -512 -> 0 rippleCoeff[y*(touchRadius*2+1)+x] = -(cos(factor*M_PI)+1.f) * 256.f; } else { rippleCoeff[y*(touchRadius*2+1)+x] = 0.f; } } } } - (void)initMesh { unsigned int index1 = 0; unsigned int index2 = 0; for (int i=0; i<poolHeight; i++) { for (int j=0; j<poolWidth; j++) { index1 = (i*poolWidth+j)*2+0; index2 = (i*poolWidth+j)*2+1; rippleVertices[index1] = -1.f + j*(2.f/(poolWidth-1)); rippleVertices[index2] = 1.f - i*(2.f/(poolHeight-1)); rippleTexCoords[index1] = (float)i/(poolHeight-1) * texCoordFactorS + texCoordOffsetS; rippleTexCoords[index2] = (1.f - (float)j/(poolWidth-1)) * texCoordFactorT + texCoordFactorT; } } unsigned int index = 0; for (int i=0; i<poolHeight-1; i++) { for (int j=0; j<poolWidth; j++) { if (i%2 == 0) { // emit extra index to create degenerate triangle if (j == 0) { rippleIndicies[index] = i*poolWidth+j; index++; } rippleIndicies[index] = i*poolWidth+j; index++; rippleIndicies[index] = (i+1)*poolWidth+j; index++; // emit extra index to create degenerate triangle if (j == (poolWidth-1)) { rippleIndicies[index] = (i+1)*poolWidth+j; index++; } } else { // emit extra index to create degenerate triangle if (j == 0) { rippleIndicies[index] = (i+1)*poolWidth+j; index++; } rippleIndicies[index] = (i+1)*poolWidth+j; index++; rippleIndicies[index] = i*poolWidth+j; index++; // emit extra index to create degenerate triangle if (j == (poolWidth-1)) { rippleIndicies[index] = i*poolWidth+j; index++; } } } } } - (GLfloat *)getVertices { return rippleVertices; } - (GLfloat *)getTexCoords { return rippleTexCoords; } - (GLushort *)getIndices { return rippleIndicies; } - (unsigned int)getVertexSize { return poolWidth*poolHeight*2*sizeof(GLfloat); } - (unsigned int)getIndexSize { return (poolHeight-1)*(poolWidth*2+2)*sizeof(GLushort); } - (unsigned int)getIndexCount { return [self getIndexSize]/sizeof(*rippleIndicies); } - (void)freeBuffers { free(rippleCoeff); free(rippleSource); free(rippleDest); free(rippleVertices); free(rippleTexCoords); free(rippleIndicies); } - (id)initWithScreenWidth:(unsigned int)width screenHeight:(unsigned int)height meshFactor:(unsigned int)factor touchRadius:(unsigned int)radius textureWidth:(unsigned int)texWidth textureHeight:(unsigned int)texHeight { self = [super init]; if (self) { screenWidth = width; screenHeight = height; meshFactor = factor; poolWidth = width/meshFactor; poolHeight = height/meshFactor; touchRadius = radius; if ((float)screenHeight/screenWidth < (float)texWidth/texHeight) { texCoordFactorS = (float)(texHeight*screenHeight)/(screenWidth*texWidth); texCoordOffsetS = (1.f - texCoordFactorS)/2.f; texCoordFactorT = 1.f; texCoordOffsetT = 0.f; } else { texCoordFactorS = 1.f; texCoordOffsetS = 0.f; texCoordFactorT = (float)(screenWidth*texWidth)/(texHeight*screenHeight); texCoordOffsetT = (1.f - texCoordFactorT)/2.f; } rippleCoeff = (float *)malloc((touchRadius*2+1)*(touchRadius*2+1)*sizeof(float)); // +2 for padding the border rippleSource = (float *)malloc((poolWidth+2)*(poolHeight+2)*sizeof(float)); rippleDest = (float *)malloc((poolWidth+2)*(poolHeight+2)*sizeof(float)); rippleVertices = (GLfloat *)malloc(poolWidth*poolHeight*2*sizeof(GLfloat)); rippleTexCoords = (GLfloat *)malloc(poolWidth*poolHeight*2*sizeof(GLfloat)); rippleIndicies = (GLushort *)malloc((poolHeight-1)*(poolWidth*2+2)*sizeof(GLushort)); if (!rippleCoeff || !rippleSource || !rippleDest || !rippleVertices || !rippleTexCoords || !rippleIndicies) { [self freeBuffers]; return nil; } [self initRippleMap]; [self initRippleCoeff]; [self initMesh]; } return self; } - (void)runSimulation { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // first pass for simulation buffers... dispatch_apply(poolHeight, queue, ^(size_t y) { for (int x=0; x<poolWidth; x++) { // * - denotes current pixel // // a // c * d // b // +1 to both x/y values because the border is padded float a = rippleSource[(y)*(poolWidth+2) + x+1]; float b = rippleSource[(y+2)*(poolWidth+2) + x+1]; float c = rippleSource[(y+1)*(poolWidth+2) + x]; float d = rippleSource[(y+1)*(poolWidth+2) + x+2]; float result = (a + b + c + d)/2.f - rippleDest[(y+1)*(poolWidth+2) + x+1]; result -= result/32.f; rippleDest[(y+1)*(poolWidth+2) + x+1] = result; } }); // second pass for modifying texture coord dispatch_apply(poolHeight, queue, ^(size_t y) { for (int x=0; x<poolWidth; x++) { // * - denotes current pixel // // a // c * d // b // +1 to both x/y values because the border is padded float a = rippleDest[(y)*(poolWidth+2) + x+1]; float b = rippleDest[(y+2)*(poolWidth+2) + x+1]; float c = rippleDest[(y+1)*(poolWidth+2) + x]; float d = rippleDest[(y+1)*(poolWidth+2) + x+2]; float s_offset = ((b - a) / 2048.f); float t_offset = ((c - d) / 2048.f); // clamp s_offset = (s_offset < -0.5f) ? -0.5f : s_offset; t_offset = (t_offset < -0.5f) ? -0.5f : t_offset; s_offset = (s_offset > 0.5f) ? 0.5f : s_offset; t_offset = (t_offset > 0.5f) ? 0.5f : t_offset; float s_tc = (float)y/(poolHeight-1) * texCoordFactorS + texCoordOffsetS; float t_tc = (1.f - (float)x/(poolWidth-1)) * texCoordFactorT + texCoordOffsetT; rippleTexCoords[(y*poolWidth+x)*2+0] = s_tc + s_offset; rippleTexCoords[(y*poolWidth+x)*2+1] = t_tc + t_offset; } }); float *pTmp = rippleDest; rippleDest = rippleSource; rippleSource = pTmp; } - (void)initiateRippleAtLocation:(CGPoint)location { unsigned int xIndex = (unsigned int)((location.x / screenWidth) * poolWidth); unsigned int yIndex = (unsigned int)((location.y / screenHeight) * poolHeight); for (int y=(int)yIndex-(int)touchRadius; y<=(int)yIndex+(int)touchRadius; y++) { for (int x=(int)xIndex-(int)touchRadius; x<=(int)xIndex+(int)touchRadius; x++) { if (x>=0 && x<poolWidth && y>=0 && y<poolHeight) { // +1 to both x/y values because the border is padded rippleSource[(poolWidth+2)*(y+1)+x+1] += rippleCoeff[(y-(yIndex-touchRadius))*(touchRadius*2+1)+x-(xIndex-touchRadius)]; } } } } - (void)dealloc { [self freeBuffers]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/RippleModel/RippleModel.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,948
```objective-c // // RippleView.h // PoppleDemo // // Created by LEA on 15/9/30. // #import <UIKit/UIKit.h> #import <GLKit/GLKit.h> #import "RippleModel.h" @interface RippleView : GLKView<GLKViewDelegate> { CADisplayLink * displayLink; BOOL stopUdpate; CGFloat _screenWidth; CGFloat _screenHeight; unsigned int _meshFactor; GLuint _program; CVImageBufferRef _pixelBuffer; CVOpenGLESTextureCacheRef _textureCache; CVOpenGLESTextureRef _texture; GLuint _positionVBO; GLuint _texcoordVBO; GLuint _indexVBO; size_t _width; size_t _height; EAGLContext *_context; } @property (nonatomic,strong) RippleModel *ripple; - (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle; - (void)render:(CADisplayLink*)displayLink; - (void)cleanRipple; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/RippleModel/RippleView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
253
```objective-c /* File: RippleModel.h Abstract: Ripple model class that simulates the ripple effect. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #import <Foundation/Foundation.h> #import <OpenGLES/ES2/gl.h> @interface RippleModel : NSObject - (GLfloat *)getVertices; - (GLfloat *)getTexCoords; - (GLushort *)getIndices; - (unsigned int)getVertexSize; - (unsigned int)getIndexSize; - (unsigned int)getIndexCount; - (id)initWithScreenWidth:(unsigned int)width screenHeight:(unsigned int)height meshFactor:(unsigned int)factor touchRadius:(unsigned int)radius textureWidth:(unsigned int)texWidth textureHeight:(unsigned int)texHeight; - (void)runSimulation; - (void)initiateRippleAtLocation:(CGPoint)location; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/RippleModel/RippleModel.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
642
```objective-c // // RippleView.m // PoppleDemo // // Created by LEA on 15/9/30. // #import "RippleView.h" #import <CoreVideo/CVOpenGLESTextureCache.h> #import <QuartzCore/QuartzCore.h> #include <stdlib.h> #import <OpenGLES/ES1/glext.h> #import <OpenGLES/ES1/gl.h> enum { UNIFORM_Y, UNIFORM_UV, UNIFORM_RGB, NUM_UNIFORMS }; GLint uniforms_ripple[NUM_UNIFORMS]; enum { ATTRIB_VERTEX, ATTRIB_TEXCOORD, ATTRIB_COLOR, NUM_ATTRIBUTES }; @implementation RippleView -(id)initWithFrame:(CGRect)frame context:(EAGLContext *)context { self = [super initWithFrame:frame context:context]; if (self) { self.delegate = self; self.context = context; self.drawableDepthFormat = GLKViewDrawableDepthFormat24; [EAGLContext setCurrentContext:context]; _context = context; // displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(render:)]; [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; displayLink.frameInterval = 3; // _meshFactor = 4; [self setupGL]; CGImageRef imageRef = [[UIImage imageNamed:@"home_top_bg"] CGImage]; imageRef = [self CGImageRotatedByAngle:imageRef angle:90.0f]; _pixelBuffer = [self pixelBufferFromCGImage:imageRef]; _width = CVPixelBufferGetWidth(_pixelBuffer); _height = CVPixelBufferGetHeight(_pixelBuffer); CVReturn err = CVOpenGLESTextureCacheCreate(kCFAllocatorDefault, NULL, (__bridge CVEAGLContext)((__bridge void *)_context), NULL, &_textureCache); if (err) { NSLog(@"Error at CVOpenGLESTextureCacheCreate %d", err); } } return self; } #pragma mark - - (void)setupGL { [EAGLContext setCurrentContext:self.context]; [self loadShaders]; glUseProgram(_program); glUniform1i(uniforms_ripple[UNIFORM_RGB], 0); } - (void)setupBuffers { glGenBuffers(1, &_indexVBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _indexVBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, [_ripple getIndexSize], [_ripple getIndices], GL_STATIC_DRAW); glGenBuffers(1, &_positionVBO); glBindBuffer(GL_ARRAY_BUFFER, _positionVBO); glBufferData(GL_ARRAY_BUFFER, [_ripple getVertexSize], [_ripple getVertices], GL_STATIC_DRAW); glEnableVertexAttribArray(ATTRIB_VERTEX); glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, 2*sizeof(GLfloat), 0); glGenBuffers(1, &_texcoordVBO); glBindBuffer(GL_ARRAY_BUFFER, _texcoordVBO); glBufferData(GL_ARRAY_BUFFER, [_ripple getVertexSize], [_ripple getTexCoords], GL_DYNAMIC_DRAW); glEnableVertexAttribArray(ATTRIB_TEXCOORD); glVertexAttribPointer(ATTRIB_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 2*sizeof(GLfloat), 0); } - (void)render:(CADisplayLink*)displayLink { GLKView* view = (GLKView*)self; [self update]; [view display]; } #pragma mark - GLKViewDelegate - (void)glkView:(GLKView *)view drawInRect:(CGRect)rect { glClear(GL_COLOR_BUFFER_BIT); if (_ripple){ unsigned int indexCount = [_ripple getIndexCount]; glDrawElements(GL_TRIANGLE_STRIP, indexCount, GL_UNSIGNED_SHORT, 0); } } #pragma mark - methods - (void)update { if(stopUdpate){ return; } if (!_textureCache){ return; } if (!_ripple){ [self loadImageIntoPond:@"home_top_bg"]; } if (_ripple) { [_ripple runSimulation]; unsigned int vertexSize = [_ripple getVertexSize]; GLfloat * texCoords = [_ripple getTexCoords]; glBufferData(GL_ARRAY_BUFFER, vertexSize, texCoords, GL_DYNAMIC_DRAW); } } -(void)loadImageIntoPond:(NSString *)fileName { [EAGLContext setCurrentContext:_context]; glDeleteBuffers(1, &_positionVBO); glDeleteBuffers(1, &_texcoordVBO); glDeleteBuffers(1, &_indexVBO); if (_ripple) _ripple = nil; _ripple = [[RippleModel alloc] initWithScreenWidth:self.frame.size.width screenHeight:self.frame.size.height meshFactor:_meshFactor touchRadius:3 textureWidth:_width textureHeight:_height]; [self setupBuffers]; glActiveTexture(GL_TEXTURE0); UIImage * image = [UIImage imageNamed:fileName]; CGImageRef spriteImage = image.CGImage; spriteImage = [self CGImageRotatedByAngle:spriteImage angle:90.0f]; if (!spriteImage) { exit(1); } _width = CGImageGetWidth(spriteImage); _height = CGImageGetHeight(spriteImage); GLubyte * spriteData = (GLubyte *) calloc(_width*_height*4, sizeof(GLubyte)); CGContextRef spriteContext = CGBitmapContextCreate(spriteData, _width, _height, 8, _width*4, CGImageGetColorSpace(spriteImage), kCGImageAlphaPremultipliedLast); CGContextDrawImage(spriteContext, CGRectMake(0, 0, _width, _height), spriteImage); CGContextRelease(spriteContext); GLuint texName; glGenTextures(1, &texName); glBindTexture(GL_TEXTURE_2D, texName); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _width, _height, 0, GL_RGBA, GL_UNSIGNED_BYTE, spriteData); free(spriteData); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } - (CVPixelBufferRef)pixelBufferFromCGImage:(CGImageRef) image { CGSize frameSize = CGSizeMake(CGImageGetWidth(image), CGImageGetHeight(image)); NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:NO], kCVPixelBufferCGImageCompatibilityKey, [NSNumber numberWithBool:NO], kCVPixelBufferCGBitmapContextCompatibilityKey, nil]; CVPixelBufferRef pxbuffer = NULL; CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, frameSize.width, frameSize.height, kCVPixelFormatType_32BGRA, (__bridge CFDictionaryRef) options, &pxbuffer); NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL); CVPixelBufferLockBaseAddress(pxbuffer, 0); void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer); CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(pxdata, frameSize.width, frameSize.height, 8, 4*frameSize.width, rgbColorSpace, kCGImageAlphaPremultipliedFirst); CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); CGColorSpaceRelease(rgbColorSpace); CGContextRelease(context); CVPixelBufferUnlockBaseAddress(pxbuffer, 0); return pxbuffer; } - (CGImageRef)CGImageRotatedByAngle:(CGImageRef)imgRef angle:(CGFloat)angle { CGFloat angleInRadians = angle * (M_PI / 180); CGFloat width = CGImageGetWidth(imgRef); CGFloat height = CGImageGetHeight(imgRef); CGRect imgRect = CGRectMake(0, 0, width, height); CGAffineTransform transform = CGAffineTransformMakeRotation(angleInRadians); CGRect rotatedRect = CGRectApplyAffineTransform(imgRect, transform); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef bmContext = CGBitmapContextCreate(NULL, rotatedRect.size.width, rotatedRect.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedFirst); CGContextSetAllowsAntialiasing(bmContext, YES); CGContextSetInterpolationQuality(bmContext, kCGInterpolationHigh); CGColorSpaceRelease(colorSpace); CGContextTranslateCTM(bmContext, +(rotatedRect.size.width/2), +(rotatedRect.size.height/2)); CGContextRotateCTM(bmContext, angleInRadians); CGContextDrawImage(bmContext, CGRectMake(-width/2, -height/2, width, height), imgRef); CGImageRef rotatedImage = CGBitmapContextCreateImage(bmContext); CFRelease(bmContext); return rotatedImage; } #pragma mark - OpenGL ES 2 shader compilation - (BOOL)loadShaders { GLuint vertShader, fragShader; NSString *vertShaderPathname, *fragShaderPathname; _program = glCreateProgram(); vertShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"vsh"]; if (![self compileShader:&vertShader type:GL_VERTEX_SHADER file:vertShaderPathname]) { return NO; } fragShaderPathname = [[NSBundle mainBundle] pathForResource:@"Shader" ofType:@"fsh"]; if (![self compileShader:&fragShader type:GL_FRAGMENT_SHADER file:fragShaderPathname]) { return NO; } glAttachShader(_program, vertShader); glAttachShader(_program, fragShader); glBindAttribLocation(_program, ATTRIB_VERTEX, "position"); glBindAttribLocation(_program, ATTRIB_TEXCOORD, "texCoord"); if (![self linkProgram:_program]) { if (vertShader) { glDeleteShader(vertShader); vertShader = 0; } if (fragShader) { glDeleteShader(fragShader); fragShader = 0; } if (_program) { glDeleteProgram(_program); _program = 0; } return NO; } uniforms_ripple[UNIFORM_RGB] = glGetUniformLocation(_program, "SamplerRGB"); if (vertShader) { glDetachShader(_program, vertShader); glDeleteShader(vertShader); } if (fragShader) { glDetachShader(_program, fragShader); glDeleteShader(fragShader); } return YES; } - (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file { GLint status; const GLchar *source; source = (GLchar *)[[NSString stringWithContentsOfFile:file encoding:NSUTF8StringEncoding error:nil] UTF8String]; if (!source) { NSLog(@"Failed to load vertex shader"); return NO; } *shader = glCreateShader(type); glShaderSource(*shader, 1, &source, NULL); glCompileShader(*shader); #if defined(DEBUG) GLint logLength; glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetShaderInfoLog(*shader, logLength, &logLength, log); NSLog(@"Shader compile log:\n%s", log); free(log); } #endif glGetShaderiv(*shader, GL_COMPILE_STATUS, &status); if (status == 0) { glDeleteShader(*shader); return NO; } return YES; } - (BOOL)linkProgram:(GLuint)prog { GLint status; glLinkProgram(prog); #if defined(DEBUG) GLint logLength; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &logLength); if (logLength > 0) { GLchar *log = (GLchar *)malloc(logLength); glGetProgramInfoLog(prog, logLength, &logLength, log); NSLog(@"Program link log:\n%s", log); free(log); } #endif glGetProgramiv(prog, GL_LINK_STATUS, &status); if (status == 0) { return NO; } return YES; } -(void) cleanRipple { if(_ripple){ _ripple = nil; } } #pragma mark - Touch handle - (void)myTouch:(NSSet *)touches withEvent:(UIEvent *)event { for (UITouch *touch in touches) { CGPoint location = [touch locationInView:touch.view]; [_ripple initiateRippleAtLocation:location]; } } - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self myTouch:touches withEvent:event]; } - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [self myTouch:touches withEvent:event]; } #pragma mark - dealloc - (void)dealloc { [self tearDownGL]; if ([EAGLContext currentContext] == self.context) { [EAGLContext setCurrentContext:nil]; } [displayLink invalidate]; displayLink = nil; } - (void)tearDownGL { [EAGLContext setCurrentContext:_context]; glDeleteBuffers(1, &_positionVBO); glDeleteBuffers(1, &_texcoordVBO); glDeleteBuffers(1, &_indexVBO); if (_program) { glDeleteProgram(_program); _program = 0; } } - (void)cleanUpTextures { if (_texture) { CFRelease(_texture); _texture = NULL; } CVOpenGLESTextureCacheFlush(_textureCache, 0); } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/05 - 水波浪/RippleModel/RippleView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,090
```objective-c // // YFOneWaterWaveViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFOneWaterWaveViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/03 - 一条水纹/YFOneWaterWaveViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
54
```objective-c // // BMWaveButton.h // Circle Button Demo // // Created by skyming on 14-6-25. // #import <UIKit/UIKit.h> typedef NS_ENUM(u_int8_t, BMWaveButtonType) { BMWaveButtonDefault = 0x00, BMWaveButtonWave = 0x02, }; @interface BMWaveButton : UIButton @property (strong, nonatomic) UIColor *borderColor; // @property (nonatomic) CGFloat borderSize; // 3.0 @property (strong, nonatomic) UIColor *waveColor; // @property (nonatomic) NSInteger timeInterval; // 45 35 @property (nonatomic) CGFloat waveDuration; // 4.0 @property (nonatomic) BOOL displayShading; // @property (nonatomic) BMWaveButtonType myButtonType; // // DefaultType BMWaveButtonDefault /** * * BMWaveButtonDefaultFrameFrame */ - (instancetype)initWithType:(BMWaveButtonType)myType; /** * * BMWaveButtonDefaultImage tinColorFrameFrame * */ - (instancetype)initWithType:(BMWaveButtonType)myType Image:(NSString *)image; /** * */ - (void)StartWave; /** * */ - (void)StopWave; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/02 - 放大水波纹2/BMWaveButton.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
269
```objective-c // // YFOneWaterWaveViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFOneWaterWaveViewController.h" #define ScreenRect [[UIScreen mainScreen] bounds] @interface YFOneWaterWaveViewController () /** * */ @property (nonatomic, strong) CAShapeLayer *shapeLayer; /** * */ @property (nonatomic, strong) CADisplayLink *displayLink; /** * */ @property (nonatomic, assign) CGFloat waterWaveHeight; /** * Y */ @property (nonatomic, assign) CGFloat zoomY; /** * X */ @property (nonatomic, assign) CGFloat translateX; @property (nonatomic, assign) BOOL flag; @end @implementation YFOneWaterWaveViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self commitInit]; [self addShapeLayer]; [self startDisplayLink]; } // - (void)commitInit { // self.waterWaveHeight = ScreenRect.size.height / 2; self.zoomY = 1.0f; self.translateX = 0.0f; self.flag = NO; } - (void)addShapeLayer { self.shapeLayer = [CAShapeLayer layer]; // self.shapeLayer.path = [self waterWavePath]; // self.shapeLayer.fillColor = [[UIColor colorWithRed:86/255.0f green:202/255.0f blue:139/255.0f alpha:1] CGColor]; // self.shapeLayer.lineWidth = 0.1; // self.shapeLayer.strokeColor = [[UIColor colorWithRed:86/255.0f green:202/255.0f blue:139/255.0f alpha:1] CGColor]; [self.view.layer addSublayer:self.shapeLayer]; } - (CGPathRef)waterWavePath { CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, nil, 0, self.waterWaveHeight); CGFloat y = 0.0f; for (float x = 0; x <= ScreenRect.size.width; x ++) { y= self.zoomY * sin( x / 180 * M_PI - 4 * self.translateX / M_PI ) * 5 + self.waterWaveHeight; CGPathAddLineToPoint(path, nil, x, y); } CGPathAddLineToPoint(path, nil, ScreenRect.size.width, ScreenRect.size.height); CGPathAddLineToPoint(path, nil, 0, ScreenRect.size.height); CGPathAddLineToPoint(path, nil, 0, self.waterWaveHeight); return (CGPathRef)path; } - (void)startDisplayLink { self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)]; [self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; } - (void)stopDisplayLink { [self.displayLink invalidate]; self.displayLink = nil; } - (void)handleDisplayLink:(CADisplayLink *)displayLink { self.translateX += 0.1;// if (!self.flag) { self.zoomY += 0.02; if (self.zoomY >= 1.5) { self.flag = YES; } } else { self.zoomY -= 0.02; if (self.zoomY <= 1.0) { self.flag = NO; } } // -- CGPathRelease(self.shapeLayer.path); self.shapeLayer.path = [self waterWavePath]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/03 - 一条水纹/YFOneWaterWaveViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
819
```objective-c // // YFRipple2ViewController.h // BigShow1949 // // Created by zhht01 on 16/1/20. // #import <UIKit/UIKit.h> @interface YFRipple2ViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/02 - 放大水波纹2/YFRipple2ViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
52
```objective-c // // YFRipple2ViewController.m // BigShow1949 // // Created by zhht01 on 16/1/20. // #import "YFRipple2ViewController.h" #import "BMWaveButton.h" @interface YFRipple2ViewController () @property (strong, nonatomic) BMWaveButton *bcnBase; @end @implementation YFRipple2ViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor grayColor]; // _bcnBase = [[BMWaveButton alloc] initWithType:BMWaveButtonDefault Image:@"YFRipple2ViewController.jpg"]; [_bcnBase StartWave]; [self.view addSubview:_bcnBase]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/02 - 放大水波纹2/YFRipple2ViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
153
```objective-c // // YFBezierViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "BaseTableViewController.h" @interface YFBezierViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/YFBezierViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
53
```objective-c // // YFBezierViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFBezierViewController.h" @interface YFBezierViewController () @end @implementation YFBezierViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupDataArr:@[@[@"",@"YFCircleViewController"], @[@"",@"YFGradientViewController"], @[@"",@"YFAliNumberViewController"], @[@"",@"YFCircleLoaderViewController"], @[@"",@"YFBounceViewController"],]]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/YFBezierViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
124
```objective-c // // YFGradientViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFGradientViewController.h" @interface YFGradientViewController () @property (strong, nonatomic) CAGradientLayer *gradientLayer; @property (strong, nonatomic) NSTimer *timer; @end @implementation YFGradientViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; //imageView UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"YFGradientViewController"]]; imageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 200); imageView.center = self.view.center; [self.view addSubview:imageView]; // self.gradientLayer = [CAGradientLayer layer]; self.gradientLayer.frame = imageView.bounds; [imageView.layer addSublayer:self.gradientLayer]; // self.gradientLayer.startPoint = CGPointMake(0, 0); self.gradientLayer.endPoint = CGPointMake(0, 1); // self.gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor, (__bridge id)[UIColor purpleColor].CGColor]; // self.gradientLayer.locations = @[@(0.5f) ,@(1.0f)]; // self.timer = [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(TimerEvent) userInfo:nil repeats:YES]; } - (void)TimerEvent { // self.gradientLayer.colors = @[(__bridge id)[UIColor clearColor].CGColor, (__bridge id)[UIColor colorWithRed:arc4random() % 255 / 255.0 green:arc4random() % 255 / 255.0 blue:arc4random() % 255 / 255.0 alpha:1.0].CGColor]; // self.gradientLayer.locations = @[@(arc4random() % 10 / 10.0f), @(1.0f)]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/02 - 渐变色/YFGradientViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
446
```objective-c // // YFGradientViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFGradientViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/02 - 渐变色/YFGradientViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // YFCircleViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFCircleViewController.h" @interface YFCircleViewController (){ double add; } //ShapeLayer @property (nonatomic, strong) CAShapeLayer *shapeLayer; @property (nonatomic, strong) NSTimer *timer; @end @implementation YFCircleViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self initCircle]; [self startAnimation]; } - (void)startAnimation { add = 0.1;//0.1 // _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(circleAnimationTypeOne) userInfo:nil repeats:YES]; } - (void)circleAnimationTypeOne { if (self.shapeLayer.strokeEnd > 1 && self.shapeLayer.strokeStart < 1) { self.shapeLayer.strokeStart += add; }else if(self.shapeLayer.strokeStart == 0){ self.shapeLayer.strokeEnd += add; } if (self.shapeLayer.strokeStart == 1) { self.shapeLayer.strokeStart = 0; self.shapeLayer.strokeEnd = 1; } // if (self.shapeLayer.strokeEnd == 0) { // self.shapeLayer.strokeStart = 0; // } // // if (self.shapeLayer.strokeStart == self.shapeLayer.strokeEnd) { // self.shapeLayer.strokeEnd = 0; // } } - (void)initCircle { //CAShapeLayer self.shapeLayer = [CAShapeLayer layer]; self.shapeLayer.frame = CGRectMake(0, 0, 200, 200);//shapeLayer self.shapeLayer.position = self.view.center; self.shapeLayer.fillColor = [UIColor clearColor].CGColor;//ClearColor // self.shapeLayer.lineWidth = 1.0f; self.shapeLayer.strokeColor = [UIColor redColor].CGColor; // UIBezierPath *circlePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)]; //CAShapeLayer self.shapeLayer.path = circlePath.CGPath; // [self.view.layer addSublayer:self.shapeLayer]; // //stroke // self.shapeLayer.strokeStart = 0.25; // 0 // self.shapeLayer.strokeEnd = 0.75; // 1 // // Stroke10.50.251/4 } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/01 - 动态圆圈/YFCircleViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
574
```objective-c // // YFCircleViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFCircleViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/01 - 动态圆圈/YFCircleViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // BMWaveButton.m // Circle Button Demo // // Created by skyming on 14-6-25. // #import "BMWaveButton.h" #define BMWaveButtonBorderWidth 0.0f #define BMWaveWidth 30 #define BMWaveTypeDefaultDuration 4.0f #define BMWaveTypeDefaultInterval 45 #define BMWaveTypeWaveDuration 4.0f #define BMWaveTypeWaveInterval 45 @interface BMWaveButton () @property (nonatomic, strong) CAGradientLayer *gradientLayerTop; @property (nonatomic, strong) CAGradientLayer *gradientLayerBottom; @property (nonatomic, strong) CADisplayLink *waveTimer; @end @implementation BMWaveButton #pragma mark- Lifecycle - (instancetype)initWithType:(BMWaveButtonType)myType { self.myButtonType = myType; UIWindow *window = [UIApplication sharedApplication].windows[0]; CGFloat midX = CGRectGetMidX(window.frame); CGFloat midY = CGRectGetMidY(window.frame); NSLog(@"MidX: %0.2f MidY: %0.2f",midX, midY); // 160 , 284 CGRect defaultFrame = CGRectMake(midX, midY, BMWaveWidth, BMWaveWidth); return [self initWithFrame:defaultFrame]; } - (instancetype)initWithType:(BMWaveButtonType)myType Image:(NSString *)image { UIImage * user =[[UIImage imageNamed:image] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [self setImage:user forState:UIControlStateNormal]; self.tintColor = [UIColor whiteColor]; return [self initWithType:myType]; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // border setting _borderColor = [UIColor whiteColor]; _borderSize = BMWaveButtonBorderWidth; // shadowOffset self.layer.shadowOffset = CGSizeMake(0.25, 0.25); //shadowOffset,x0.25y0.25(0, -3),shadowRadius self.layer.shadowRadius = 0.0; //3 self.layer.shadowColor = [UIColor blackColor].CGColor; // self.layer.shadowOpacity = 0.5; //0 // gradientLayer _gradientLayerTop = [CAGradientLayer layer]; _gradientLayerTop.frame = CGRectMake(0.0, 0.0, frame.size.width, frame.size.height / 4); _gradientLayerTop.colors = @[(id)[UIColor orangeColor].CGColor, (id)[[UIColor greenColor] colorWithAlphaComponent:0.01].CGColor]; _gradientLayerBottom = [CAGradientLayer layer]; _gradientLayerBottom.frame = CGRectMake(0.0, frame.size.height * 3 / 4, frame.size.width, frame.size.height / 4); _gradientLayerBottom.colors = @[(id)[[UIColor orangeColor] colorWithAlphaComponent:0.01].CGColor, (id)[UIColor greenColor].CGColor]; self.clipsToBounds = YES; self.layer.cornerRadius = CGRectGetWidth(self.frame)/2.0; if (self.myButtonType == BMWaveButtonWave) { _timeInterval = 35; _waveDuration = 4.0; }else{ _timeInterval = 45; _waveDuration = 4.0; } } return self; } #pragma mark- Custom Accessors - (void)setBorderColor:(UIColor *)borderColor { _borderColor = borderColor; [self layoutSubviews]; } - (void)setBorderSize:(CGFloat)borderSize { _borderSize = borderSize; [self layoutSubviews]; } - (void)setDisplayShading:(BOOL)displayShading { _displayShading = displayShading; if (displayShading) { [self.layer addSublayer:self.gradientLayerTop]; [self.layer addSublayer:self.gradientLayerBottom]; } else { [self.gradientLayerTop removeFromSuperlayer]; [self.gradientLayerBottom removeFromSuperlayer]; } [self layoutSubviews]; } - (void)setSelected:(BOOL)selected { if (selected) { self.layer.borderColor = [self.borderColor colorWithAlphaComponent:1.0].CGColor; [_waveTimer invalidate]; }else { self.layer.borderColor = [self.borderColor colorWithAlphaComponent:0.7].CGColor; [self StartWave]; } } #pragma mark- Private - (void)updateMaskToBounds:(CGRect)maskBounds { CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; CGPathRef maskPath = CGPathCreateWithEllipseInRect(maskBounds, NULL); maskLayer.bounds = maskBounds; maskLayer.path = maskPath; maskLayer.fillColor = [UIColor blackColor].CGColor; CGPoint point = CGPointMake(maskBounds.size.width/2, maskBounds.size.height/2); maskLayer.position = point; [self.layer setMask:maskLayer]; self.layer.cornerRadius = CGRectGetHeight(maskBounds) / 2.0; self.layer.borderColor = [self.borderColor colorWithAlphaComponent:0.7].CGColor; self.layer.borderWidth = self.borderSize; } - (void)waveAnimate { CGRect pathFrame = CGRectMake(-CGRectGetMidX(self.bounds), -CGRectGetMidY(self.bounds), self.bounds.size.width, self.bounds.size.height); UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:pathFrame cornerRadius:self.layer.cornerRadius]; // accounts for left/right offset and contentOffset of scroll view CGPoint shapePosition = [self.superview convertPoint:self.center fromView:self.superview]; CAShapeLayer *circleShape = [CAShapeLayer layer]; circleShape.path = path.CGPath; circleShape.position = shapePosition; circleShape.opacity = 0; circleShape.strokeColor = self.borderColor.CGColor; if (self.myButtonType == BMWaveButtonDefault) { circleShape.lineWidth = 0.25; circleShape.fillColor = [UIColor clearColor].CGColor; }else if(self.myButtonType == BMWaveButtonWave) { circleShape.lineWidth = 0.0; if (self.waveColor) { circleShape.fillColor = self.waveColor.CGColor; }else{ // circleShape.fillColor = [UIColor colorWithRed:0.821 green:0.832 blue:0.842 alpha:1.000].CGColor; } } [self.superview.layer addSublayer:circleShape]; CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; scaleAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity]; NSInteger scaleLength = 13; CGFloat alplaValue = 0.3; scaleAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(scaleLength, scaleLength, 1)]; CABasicAnimation *alphaAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; alphaAnimation.fromValue = @(alplaValue); alphaAnimation.toValue = @0; CAAnimationGroup *animation = [CAAnimationGroup animation]; animation.animations = @[scaleAnimation, alphaAnimation]; animation.duration = _waveDuration; animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut]; [circleShape addAnimation:animation forKey:nil]; } - (void)layoutSubviews { [super layoutSubviews]; [self updateMaskToBounds:self.bounds]; } #pragma mark- Public - (void)StopWave { [_waveTimer invalidate]; } - (void)StartWave { _waveTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(waveAnimate)]; [_waveTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [_waveTimer setFrameInterval:_timeInterval]; } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. - (void)drawRect:(CGRect)rect { // Drawing code } */ @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/03 - 水纹/02 - 放大水波纹2/BMWaveButton.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,777
```objective-c // // YFAliNumberViewController.h // BigShow1949 // // Created by apple on 16/8/19. // #import <UIKit/UIKit.h> @interface YFAliNumberViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/YFAliNumberViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // UILabel+BezierAnimation.h // Test // // Created by senro wang on 15/8/11. // #import <UIKit/UIKit.h> @interface UILabel (BezierAnimation) //label - (void)animationFromnum:(float )fromNum toNum:(float )toNum duration:(float )duration; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/UILabel+BezierAnimation.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
74
```objective-c // // WSBezier.m // Test // // Created by senro wang on 15/8/11. // #import "WSBezier.h" @implementation WSBezier - (instancetype)init{ if (self = [super init]) { [self _initPoints]; } return self; } - (void)_initPoints{ WSPoint start; WSPoint first; WSPoint second; WSPoint end; start.x = 0; start.y = 0; first.x = 0; first.y = 0.57; second.x = 0.44; second.y = 1; end.x = 1; end.y = 1; self.wsStart = start; self.wsFirst = first; self.wsSecond = second; self.wsEnd = end; } // //y=y0(1-t)+3y1t(1-t)+3y2t(1-t)+y3t //x=x0(1-t)+3x1t(1-t)+3x2t(1-t)+x3t // //0 0 (0 , 0.57) (0.44 , 1 ) (1 ,1); // // ease in ease out ease inout spring 840787626@qq.com // diy //path_to_url#0,.57,.44,1 - (WSPoint)pointWithdt:(float )dt{ WSPoint result; float t = 1 - dt; float tSqure = t * t; float tCube = t * tSqure; float dtSqure = dt * dt; float dtCube = dtSqure * dt; result.x = self.wsStart.x * tCube + 3 * self.wsFirst.x * dt * tSqure + 3 * self.wsSecond.x * dtSqure * t + self.wsEnd.x * dtCube; result.y = self.wsStart.y * tCube + 3 * self.wsFirst.y * dt * tSqure + 3 * self.wsSecond.y * dtSqure * t + self.wsEnd.y * dtCube; return result; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/WSBezier.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
500
```objective-c // // UILabel+BezierAnimation.m // Test // // Created by senro wang on 15/8/11. // #import "UILabel+BezierAnimation.h" #import "WSBezier.h" #define KMaxTimes 100 @implementation UILabel (BezierAnimation) NSMutableArray *totlePoints; // WSBezier *bezier; // bezier float _duration; // float _fromNum; float _toNum; float _lastTime; // int _index; //- (instancetype)initWithFrame:(CGRect)frame{ // // if (self = [super initWithFrame:frame]) { // //// [self _initBezier]; //// [self _cleanVars]; // } // // return self; //} - (void)_cleanVars{ _lastTime = 0; _index = 0; // self.text = @"0"; } // - (void)_initBezier{ bezier = [[WSBezier alloc] init]; } - (void)animationFromnum:(float)fromNum toNum:(float)toNum duration:(float)duration{ [self _cleanVars]; [self _initBezier]; _duration = duration; _fromNum = fromNum; _toNum = toNum; totlePoints = [NSMutableArray array]; float dt = 1.0 / (KMaxTimes - 1); for (NSInteger i = 0; i < KMaxTimes; i ++ ) { WSPoint point = [bezier pointWithdt:dt * i]; float currTime = point.x * _duration; float currValue = point.y * (_toNum - _fromNum) + _fromNum; NSArray *array = [NSArray arrayWithObjects:[NSNumber numberWithFloat:currTime] , [NSNumber numberWithFloat:currValue], nil]; [totlePoints addObject:array]; } [self changeNumberBySelector]; } - (void)changeNumberBySelector { if (_index>= KMaxTimes) { self.text = [NSString stringWithFormat:@"%.0f",_toNum]; return; } else { NSArray *pointValues = [totlePoints objectAtIndex:_index]; _index++; float value = [(NSNumber *)[pointValues objectAtIndex:1] intValue]; float currentTime = [(NSNumber *)[pointValues objectAtIndex:0] floatValue]; float timeDuration = currentTime - _lastTime; _lastTime = currentTime; self.text = [NSString stringWithFormat:@"%.0f",value]; [self performSelector:@selector(changeNumberBySelector) withObject:nil afterDelay:timeDuration]; } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/UILabel+BezierAnimation.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
566
```objective-c // // YFAliNumberViewController.m // BigShow1949 // // Created by apple on 16/8/19. // #import "YFAliNumberViewController.h" #import "UILabel+BezierAnimation.h" @interface YFAliNumberViewController () @end @implementation YFAliNumberViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; UILabel *label = [[UILabel alloc] init]; label.frame = CGRectMake(100, 100, 100, 30); label.backgroundColor = [UIColor lightGrayColor]; [label animationFromnum:0 toNum:1000 duration:3]; [self.view addSubview:label]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/YFAliNumberViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
238
```objective-c // // WSBezier.h // Test // // Created by senro wang on 15/8/11. // #import <Foundation/Foundation.h> typedef struct { float x; float y; } WSPoint; @interface WSBezier : NSObject @property (nonatomic,assign) WSPoint wsStart; @property (nonatomic,assign) WSPoint wsFirst; @property (nonatomic,assign) WSPoint wsSecond; @property (nonatomic,assign) WSPoint wsEnd; - (WSPoint )pointWithdt:(float )dt; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/仿支付宝余额跳动/WSBezier.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
112
```objective-c // // YFCircleLoader.h // BigShow1949 // // Created by apple on 16/8/23. // #import <UIKit/UIKit.h> @interface CircleLoader : UIView // @property(nonatomic, retain) UIColor* progressTintColor ; // @property(nonatomic, retain) UIColor* trackTintColor ; // @property (nonatomic,assign) float lineWidth; // @property (nonatomic,strong) UIImage *centerImage; // @property (nonatomic,assign) float progressValue; // @property (nonatomic,strong) NSString *promptTitle; // @property (nonatomic,assign) BOOL animationing; // - (void)hide; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/加载框/YFCircleLoader.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
126
```objective-c // // YFCircleLoaderViewController.h // BigShow1949 // // Created by apple on 16/8/23. // #import <UIKit/UIKit.h> @interface YFCircleLoaderViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/加载框/YFCircleLoaderViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // YFCircleLoaderViewController.m // BigShow1949 // // Created by apple on 16/8/23. // #import "YFCircleLoaderViewController.h" #import "YFCircleLoader.h" @interface YFCircleLoaderViewController () @end @implementation YFCircleLoaderViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; // CircleLoader *view=[[CircleLoader alloc]initWithFrame:CGRectMake(100, 100, 70, 70)]; // view.trackTintColor=[UIColor redColor]; // view.progressTintColor=[UIColor greenColor]; // view.lineWidth=5.0; // view.progressValue=0.7; // YES view.animationing=YES; // // view.centerImage=[UIImage imageNamed:@"yzp_loading"]; // [self.view addSubview:view]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ // // [view hide]; }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/加载框/YFCircleLoaderViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
319
```objective-c // // YFBounceViewController.m // BigShow1949 // // Created by apple on 16/8/23. // #import "YFBounceViewController.h" #import "BounceView.h" @interface YFBounceViewController () @end @implementation YFBounceViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor blueColor]; BounceView *view = [[BounceView alloc] init]; view.backgroundColor = [UIColor lightGrayColor]; view.frame = self.view.bounds; [self.view addSubview:view]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/手势控制贝塞尔曲线/YFBounceViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
125
```objective-c // // BounceView.h // KYBezierBounceView // // Created by Kitten Yang on 2/17/15. // #import <UIKit/UIKit.h> @interface BounceView : UIView @property(nonatomic,strong)CAShapeLayer * verticalLineLayer; @property(nonatomic,strong)UIPanGestureRecognizer *sgr; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/手势控制贝塞尔曲线/BounceView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
72
```objective-c // // YFBounceViewController.h // BigShow1949 // // Created by apple on 16/8/23. // #import <UIKit/UIKit.h> @interface YFBounceViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/手势控制贝塞尔曲线/YFBounceViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
48
```objective-c // // YFCircleLoader.m // BigShow1949 // // Created by apple on 16/8/23. // #import "YFCircleLoader.h" @interface CircleLoader () @property (nonatomic,strong) CAShapeLayer *trackLayer; @property (nonatomic,strong) CAShapeLayer *progressLayer; @end @implementation CircleLoader - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor=[UIColor clearColor]; } return self; } -(void)drawRect:(CGRect)rect { [super drawRect:rect]; _trackLayer=[CAShapeLayer layer]; _trackLayer.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); _trackLayer.lineWidth=_lineWidth; _trackLayer.strokeColor=_trackTintColor.CGColor; _trackLayer.fillColor = self.backgroundColor.CGColor; _trackLayer.lineCap = kCALineCapRound; [self.layer addSublayer:_trackLayer]; _progressLayer=[CAShapeLayer layer]; _progressLayer.frame=CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); _progressLayer.lineWidth=_lineWidth; _progressLayer.strokeColor=_progressTintColor.CGColor; _progressLayer.fillColor = self.backgroundColor.CGColor; _progressLayer.lineCap = kCALineCapRound; [self.layer addSublayer:_progressLayer]; if (_centerImage!=nil) { UIImageView *centerImgView=[[UIImageView alloc]initWithImage:_centerImage]; centerImgView.frame=CGRectMake(_lineWidth, _lineWidth, self.frame.size.width-2*_lineWidth, self.frame.size.height-_lineWidth*2); // centerImgView.center=self.center; centerImgView.layer.cornerRadius=(self.frame.size.width+_lineWidth)/2; centerImgView.clipsToBounds=YES; [self.layer addSublayer:centerImgView.layer]; } [self start]; } - (void)drawBackgroundCircle:(BOOL) animationing { // 0 M_PI/2 CGFloat startAngle = - ((float)M_PI / 2); // 90 Degrees // CGFloat endAngle = (2 * (float)M_PI) + - ((float)M_PI / 8);; CGPoint center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); CGFloat radius = (self.bounds.size.width - _lineWidth)/2; UIBezierPath *processPath = [UIBezierPath bezierPath]; // processPath.lineWidth=_lineWidth; UIBezierPath *trackPath = [UIBezierPath bezierPath]; // trackPath.lineWidth=_lineWidth; //--------------------------------------- // Make end angle to 90% of the progress //--------------------------------------- if (!animationing) { endAngle = (_progressValue * 2*(float)M_PI) + startAngle; } else { endAngle = (0.1 * 2*(float)M_PI) + startAngle; } [processPath addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES]; [trackPath addArcWithCenter:center radius:radius startAngle:0 endAngle:2*M_PI clockwise:YES]; _progressLayer.path = processPath.CGPath; _trackLayer.path=trackPath.CGPath; } - (void)start { [self drawBackgroundCircle:_animationing]; if (_animationing) { CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"]; rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0]; rotationAnimation.duration = 1; rotationAnimation.cumulative = YES; rotationAnimation.repeatCount = HUGE_VALF; [_progressLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"]; } } - (void)hide { [_progressLayer removeAllAnimations]; [self removeFromSuperview]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/加载框/YFCircleLoader.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
859
```objective-c // // UITextField+test.h // test2 // // Created by apple on 16/8/24. // #import <UIKit/UIKit.h> @interface UITextField (Shake) - (void)shakeWithCompletion:(void (^)())completion; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/抖动密码框/UITextField+Shake.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
57
```objective-c // // UITextField+test.m // test2 // // Created by apple on 16/8/24. // #import "UITextField+Shake.h" #import <objc/runtime.h> @interface UITextField (Shake) typedef void (^Completion)(); @property (nonatomic, copy) Completion completionBlock; @end @implementation UITextField (Shake) static char const *strAddrKey = "strAddrKey"; - (Completion)completionBlock { return objc_getAssociatedObject(self, strAddrKey); } - (void)setCompletionBlock:(Completion)completionBlock { objc_setAssociatedObject(self, strAddrKey, completionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC); } - (void)shakeWithCompletion:(void (^)())completion { self.completionBlock = completion; [self _shake:10 direction:1 currentTimes:0 withDelta:5 andSpeed:0.03]; } /** * * * @param times * @param direction : * @param current * @param delta * @param interval */ - (void)_shake:(int)times direction:(int)direction currentTimes:(int)current withDelta:(CGFloat)delta andSpeed:(NSTimeInterval)interval { [UIView animateWithDuration:interval animations:^{ self.transform = CGAffineTransformMakeTranslation(delta * direction, 0); } completion:^(BOOL finished) { if(current >= times) { self.transform = CGAffineTransformIdentity; if (self.completionBlock) { self.completionBlock(); } }else { [self _shake:(times - 1) direction:direction * -1 currentTimes:current + 1 withDelta:delta andSpeed:interval]; } }]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/抖动密码框/UITextField+Shake.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
374
```objective-c // // YFPasswordShakeViewController.h // BigShow1949 // // Created by apple on 16/8/24. // #import <UIKit/UIKit.h> @interface YFPasswordShakeViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/抖动密码框/YFPasswordShakeViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
52
```objective-c // // YFPasswordShakeViewController.m // BigShow1949 // // Created by apple on 16/8/24. // #import "YFPasswordShakeViewController.h" #import "UITextField+Shake.h" @interface YFPasswordShakeViewController () @property (nonatomic, strong) UITextField *textField; @end @implementation YFPasswordShakeViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; UITextField *textField = [[UITextField alloc] init]; textField.text = @"textField"; textField.frame = CGRectMake(50, 100, 100, 30); textField.layer.borderColor = [UIColor blackColor].CGColor; textField.layer.borderWidth = 1.0f; [self.view addSubview:textField]; self.textField = textField; UIButton *redBtn = [[UIButton alloc] init]; redBtn.frame = CGRectMake(100, 200, 100, 100); [redBtn setTitle:@"click here" forState:UIControlStateNormal]; [redBtn addTarget:self action:@selector(redBtnClick:) forControlEvents:UIControlEventTouchUpInside]; redBtn.backgroundColor = [UIColor redColor]; [self.view addSubview:redBtn]; } - (void)redBtnClick:(UIButton *)redBtn { [self.textField shakeWithCompletion:^{ NSLog(@""); }]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/抖动密码框/YFPasswordShakeViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
281
```objective-c // // YFEmitterViewController.m // BigShow1949 // // Created by on 15-9-4. // #import "YFEmitterViewController.h" @implementation YFEmitterViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupDataArr:@[@[@"",@"YFSnowViewController"]]]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/YFEmitterViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
77
```objective-c // // YFEmitterViewController.h // BigShow1949 // // Created by on 15-9-4. // #import <UIKit/UIKit.h> @interface YFEmitterViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/YFEmitterViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
50
```objective-c // // YFSnowViewController.h // BigShow1949 // // Created by on 15-9-4. // #import <UIKit/UIKit.h> @interface YFSnowViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFSnowViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
48
```objective-c // // YFSnowViewController.m // BigShow1949 // // Created by on 15-9-4. // #import "YFSnowViewController.h" #import "YFAnimationManager.h" @interface YFSnowViewController () @end @implementation YFSnowViewController - (void)viewDidLoad { [super viewDidLoad]; self.title = @""; self.view.backgroundColor = [UIColor lightGrayColor]; [[YFAnimationManager shareInstancetype] showAnimationInView:self.view withAnimationStyle:YFAnimationStyleOfSnow]; // } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFSnowViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
121
```objective-c // // CAEmitterSnowCell.h // Snowing // // Created by ykh on 15/1/16. // #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import "UIImage+Extension.h" #import "YFPublicParticleCell.h" @interface YFEmitterSnowCell : YFPublicParticleCell /** * ,,, * * @param cellImg * @param radious * @param velocity * * @return */ +(instancetype)snowCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/SnowCell/YFEmitterSnowCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
151
```objective-c // // CAEmitterSnowCell.m // Snowing // // Created by ykh on 15/1/16. // #import "YFEmitterSnowCell.h" @implementation YFEmitterSnowCell +(instancetype)snowCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction { NSLog(@"snowCellWithCellImg "); NSString * const snowPic = @"snow.png";// YFEmitterSnowCell *cell=[[self alloc] init]; // cell.name = @"snow"; // UIImage *img; if (cellImg.length==0) { img=[UIImage imageNamed:snowPic]; }else{ img=[UIImage imageNamed:cellImg]; } // img=[UIImage image:img scaleToSize:CGSizeMake(radious, radious)]; cell.contents=(id)[img CGImage]; // cell.velocity=radious*3; // switch (direction) { case YFEmitterParticleCellDirectionToLeft: //,y,x,, cell.xAcceleration=-1; // cell.emissionRange = -0.5* M_PI; break; case YFEmitterParticleCellDirectionToRight: cell.xAcceleration=1; cell.emissionRange = 0.25* M_PI; break; case YFEmitterParticleCellDirectionToTop: cell.yAcceleration=-1; cell.emissionRange = 0.5* M_PI; break; case YFEmitterParticleCellDirectionToBottom: cell.yAcceleration=1; cell.emissionRange = 0.5* M_PI; break; } return cell; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/SnowCell/YFEmitterSnowCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
387
```objective-c // // BounceView.m // KYBezierBounceView // // Created by Kitten Yang on 2/17/15. // #import "BounceView.h" @implementation BounceView{ UIView *leftBubble; UIView *righBubble; } -(id)initWithCoder:(NSCoder *)aDecoder{ self = [super initWithCoder:aDecoder]; if (self) { [self createLine]; [self addPanGesture]; } return self; } -(id)initWithFrame:(CGRect)frame{ self = [super initWithFrame:frame]; if (self) { [self createLine]; [self addPanGesture]; } return self; } - (void) createLine { self.verticalLineLayer = [CAShapeLayer layer]; self.verticalLineLayer.strokeColor = [[UIColor whiteColor] CGColor]; self.verticalLineLayer.lineWidth = 1.0; self.verticalLineLayer.fillColor = [[UIColor whiteColor] CGColor]; [self.layer addSublayer:self.verticalLineLayer]; } - (void) addPanGesture { self.sgr = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleSlide:)]; [self addGestureRecognizer:self.sgr]; } // - (CGPathRef) getLeftLinePathWithAmount:(CGFloat)amount { UIBezierPath *verticalLine = [UIBezierPath bezierPath]; CGPoint topPoint = CGPointMake(0, 0); CGPoint midControlPoint = CGPointMake(amount, self.bounds.size.height/2); CGPoint bottomPoint = CGPointMake(0, self.bounds.size.height); [verticalLine moveToPoint:topPoint]; [verticalLine addQuadCurveToPoint:bottomPoint controlPoint:midControlPoint]; [verticalLine closePath]; return [verticalLine CGPath]; } // -(CGPathRef) getRightLinePathWithAmount:(CGFloat)amount{ UIBezierPath *verticalLine = [UIBezierPath bezierPath]; CGPoint topPoint = CGPointMake(self.bounds.size.width , 0); CGPoint midControlPoint = CGPointMake(self.bounds.size.width - amount, self.bounds.size.height/2); CGPoint bottomPoint = CGPointMake(self.bounds.size.width , self.bounds.size.height); [verticalLine moveToPoint:topPoint]; [verticalLine addQuadCurveToPoint:bottomPoint controlPoint:midControlPoint]; [verticalLine closePath]; return [verticalLine CGPath]; } - (void) handleSlide:(UIPanGestureRecognizer *)gr{ CGFloat amountX = [gr translationInView:self].x; CGFloat amountY = [gr translationInView:self].y; if ( ABS(amountY) > ABS(amountX)) { [self cancelPost]; [self cancelComment]; return; } if (gr.state == UIGestureRecognizerStateChanged){ if (amountX >= 0) { if (leftBubble == nil) { leftBubble = [[UIView alloc]init]; leftBubble.center = CGPointMake(-100, self.bounds.size.height / 2); leftBubble.bounds = CGRectMake(0, 0, 100, 100); leftBubble.backgroundColor = [UIColor redColor]; leftBubble.layer.cornerRadius = 50; [self addSubview:leftBubble]; } // [self cancelComment]; self.verticalLineLayer.path = [self getLeftLinePathWithAmount:amountX]; leftBubble.frame = CGRectMake(-100 + amountX*0.4, leftBubble.frame.origin.y, 100, 100); if (amountX > self.bounds.size.width / 2) { [UIView animateWithDuration:0.5f delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{ leftBubble.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2); } completion:^(BOOL finished) { [self cancelPost]; }]; [self removeGestureRecognizer:gr]; [self animateLeftLineReturnFrom:amountX]; } }else{ if (righBubble == nil) { righBubble = [[UIView alloc]init]; righBubble.center = CGPointMake(self.bounds.size.width + 100, self.bounds.size.height / 2); righBubble.bounds = CGRectMake(0, 0, 100, 100); righBubble.backgroundColor = [UIColor blueColor]; righBubble.layer.cornerRadius = 50; [self addSubview:righBubble]; } // [self cancelPost]; self.verticalLineLayer.path = [self getRightLinePathWithAmount:fabs(amountX)]; righBubble.frame = CGRectMake(self.bounds.size.width + amountX*0.4, righBubble.frame.origin.y, 100, 100); if (fabs(amountX) > self.bounds.size.width / 2) { [UIView animateWithDuration:0.5f delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{ righBubble.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2); } completion:^(BOOL finished) { [self cancelComment]; }]; [self removeGestureRecognizer:gr]; [self animateRightLineReturnFrom:fabs(amountX)]; } } } if (gr.state == UIGestureRecognizerStateEnded || gr.state == UIGestureRecognizerStateCancelled || gr.state == UIGestureRecognizerStateFailed) { [self cancelPost]; [self cancelComment]; if (amountX >= 0) { [self removeGestureRecognizer:gr]; [self animateLeftLineReturnFrom:amountX]; }else{ [self removeGestureRecognizer:gr]; [self animateRightLineReturnFrom:fabs(amountX)]; } } } -(void)cancelPost{ [UIView animateWithDuration:0.8f delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{ leftBubble.center = CGPointMake(-100, self.bounds.size.height / 2); } completion:^(BOOL finished) { [leftBubble removeFromSuperview]; leftBubble = nil; }]; } -(void)cancelComment{ [UIView animateWithDuration:0.8f delay:0.0f usingSpringWithDamping:0.6f initialSpringVelocity:0.0f options:UIViewAnimationOptionCurveEaseInOut animations:^{ righBubble.center = CGPointMake(self.bounds.size.width + 100, self.bounds.size.height / 2); } completion:^(BOOL finished) { [righBubble removeFromSuperview]; righBubble = nil; }]; } - (void) animateLeftLineReturnFrom:(CGFloat)positionX { // ----- ANIMATION WITH BOUNCE CAKeyframeAnimation *morph = [CAKeyframeAnimation animationWithKeyPath:@"path"]; morph.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; NSArray *values = @[ (id) [self getLeftLinePathWithAmount:positionX], (id) [self getLeftLinePathWithAmount:-(positionX * 0.9)], (id) [self getLeftLinePathWithAmount:(positionX * 0.6)], (id) [self getLeftLinePathWithAmount:-(positionX * 0.4)], (id) [self getLeftLinePathWithAmount:(positionX * 0.25)], (id) [self getLeftLinePathWithAmount:-(positionX * 0.15)], (id) [self getLeftLinePathWithAmount:(positionX * 0.05)], (id) [self getLeftLinePathWithAmount:0.0] ]; morph.values = values; morph.duration = 0.5; morph.removedOnCompletion = NO; morph.fillMode = kCAFillModeForwards; morph.delegate = self; [self.verticalLineLayer addAnimation:morph forKey:@"bounce_left"]; } - (void) animateRightLineReturnFrom:(CGFloat)positionX { // ----- ANIMATION WITH BOUNCE CAKeyframeAnimation *morph = [CAKeyframeAnimation animationWithKeyPath:@"path"]; morph.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; NSArray *values = @[ (id) [self getRightLinePathWithAmount:positionX], (id) [self getRightLinePathWithAmount:-(positionX * 0.9)], (id) [self getRightLinePathWithAmount:(positionX * 0.6)], (id) [self getRightLinePathWithAmount:-(positionX * 0.4)], (id) [self getRightLinePathWithAmount:(positionX * 0.25)], (id) [self getRightLinePathWithAmount:-(positionX * 0.15)], (id) [self getRightLinePathWithAmount:(positionX * 0.05)], (id) [self getRightLinePathWithAmount:0.0] ]; morph.values = values; morph.duration = 0.5; morph.removedOnCompletion = NO; morph.fillMode = kCAFillModeForwards; morph.delegate = self; [self.verticalLineLayer addAnimation:morph forKey:@"bounce_right"]; } #pragma mark - CAAnimationDelegate - (void) animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { if (anim == [self.verticalLineLayer animationForKey:@"bounce_left"] ) { self.verticalLineLayer.path = [self getLeftLinePathWithAmount:0.0]; [self.verticalLineLayer removeAllAnimations]; [self addPanGesture]; }else if(anim == [self.verticalLineLayer animationForKey:@"bounce_right"]){ self.verticalLineLayer.path = [self getRightLinePathWithAmount:0.0]; [self.verticalLineLayer removeAllAnimations]; [self addPanGesture]; } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/04 - 渐变色和贝塞尔曲线/手势控制贝塞尔曲线/BounceView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,160
```objective-c // // CAEmitterleavesCell.h // leavesing // // Created by ykh on 15/1/16. // #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import "UIImage+Extension.h" #import "YFPublicParticleCell.h" @interface YFEmitterLeavesCell : YFPublicParticleCell /** * ,,, * * @param cellImg * @param radious * @param velocity * * @return */ +(instancetype)leavesCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/LevaesCell/YFEmitterLeavesCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
154
```objective-c // // PublicParticleCell.m // YFAnimationStyle // // Created by ykh on 15/5/28. // #import "YFPublicParticleCell.h" @implementation YFPublicParticleCell -(instancetype)init{ if (self=[super init]) { // self = (YFPublicParticleCell *)[CAEmitterCell emitterCell]; // self.name = @"snow"; // //, self.birthRate = 1.5; // self.lifetime = 60.0; //, // self.velocityRange = self.velocity; // self.spinRange = 0.5 * M_PI; } return self; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/PublicParticleCell/YFPublicParticleCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
155
```objective-c // // CAEmitterleavesCell.m // leavesing // // Created by ykh on 15/1/16. // #import "YFEmitterLeavesCell.h" @implementation YFEmitterLeavesCell +(instancetype)leavesCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction { NSString * const leavesPic = @"leaves.png";// YFEmitterLeavesCell *cell=(YFEmitterLeavesCell *)[[self alloc] init]; cell.birthRate = 0.3; cell.name = @"leaves"; // UIImage *img; if (cellImg.length==0) { img=[UIImage imageNamed:leavesPic]; }else{ img=[UIImage imageNamed:cellImg]; } // img=[UIImage image:img scaleToSize:CGSizeMake(radious, radious)]; cell.contents=(id)[img CGImage]; // cell.velocity=radious*2; // switch (direction) { case YFEmitterParticleCellDirectionToLeft: //,y,x,, cell.xAcceleration=-1; // cell.emissionRange = -0.5* M_PI; break; case YFEmitterParticleCellDirectionToRight: cell.xAcceleration=1; cell.emissionRange = 0.25* M_PI; break; case YFEmitterParticleCellDirectionToTop: cell.yAcceleration=-1; cell.emissionRange = 0.5* M_PI; break; case YFEmitterParticleCellDirectionToBottom: cell.yAcceleration=1; cell.emissionRange = 0.5* M_PI; break; } return cell; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/LevaesCell/YFEmitterLeavesCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
402
```objective-c // // PublicParticleCell.h // YFAnimationStyle // // Created by ykh on 15/5/28. // #import <QuartzCore/QuartzCore.h> // typedef enum{ YFEmitterParticleCellDirectionToLeft, YFEmitterParticleCellDirectionToRight, YFEmitterParticleCellDirectionToTop, YFEmitterParticleCellDirectionToBottom, } YFEmitterParticleCellDirection; @interface YFPublicParticleCell : CAEmitterCell @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/PublicParticleCell/YFPublicParticleCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
107
```objective-c // // YFEmitterCustomLayer.h // Snowing // // Created by ykh on 15/1/16. // #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import "YFEmitterSnowCell.h" @interface YFEmitterCustomLayer : CAEmitterLayer /** * view * * @param view view */ + (void)addSnowLayerInView:(UIView *)view; /** * view * * @param view view */ + (void)addleavesLayerInView:(UIView *)view; /** * view * * @param view view */ + (void)addRainLayerInView:(UIView *)view; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/EmitterLayer/YFEmitterCustomLayer.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
152
```objective-c // // YFEmitterCustomLayer.m // Snowing // // Created by ykh on 15/1/16. // #import "YFEmitterCustomLayer.h" #import "UIImage+Extension.h" #import "YFEmitterLeavesCell.h" #import "YFEmitterSnowCell.h" #import "YFEmitterRainCell.h" @implementation YFEmitterCustomLayer #pragma mark //, + (instancetype)addCustomLayerInView:(UIView *)view atPosition:(CGPoint)position inSize:(CGSize)size { YFEmitterCustomLayer *leavesEmitter = (YFEmitterCustomLayer*)[CAEmitterLayer layer]; // leavesEmitter.emitterPosition = position; leavesEmitter.emitterSize = CGSizeMake(size.width, size.height); // view.layer.masksToBounds=YES; // leavesEmitter.emitterMode = kCAEmitterLayerSurface; //, leavesEmitter.shadowColor = [[UIColor whiteColor] CGColor]; //viewlayer [view.layer addSublayer:leavesEmitter]; return leavesEmitter; } #pragma mark + (void)leavesLayerInView:(UIView *)view atPosition:(CGPoint)position andDirection:(YFEmitterParticleCellDirection)direction andRadious:(CGFloat)radious andCellImg:(NSString *)cellImg { //layer YFEmitterCustomLayer *leavesLayer = [self addCustomLayerInView:view atPosition:position inSize:CGSizeMake(view.frame.size.width, view.frame.size.height)]; // YFEmitterLeavesCell *emitterCell = [YFEmitterLeavesCell leavesCellWithCellImg:cellImg andRadious:radious andVelocity:20 andDirection:direction]; leavesLayer.emitterCells = @[emitterCell]; } + (void)addleavesLayerInView:(UIView *)view { //view,,,, [YFEmitterCustomLayer leavesLayerInView:view atPosition:CGPointMake(-60,-20) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:19 andCellImg:nil]; [YFEmitterCustomLayer leavesLayerInView:view atPosition:CGPointMake(-60,-20) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:9 andCellImg:nil]; [YFEmitterCustomLayer leavesLayerInView:view atPosition:CGPointMake(-60,view.frame.size.height*0.33) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:14 andCellImg:nil]; } #pragma mark +(void)snowLayerInView:(UIView *)view atPosition:(CGPoint)position andDirection:(YFEmitterParticleCellDirection)direction andRadious:(CGFloat)radious andCellImg:(NSString *)cellImg { NSLog(@" - snowLayerInView"); //layer YFEmitterCustomLayer *snowLayer=[self addCustomLayerInView:view atPosition:position inSize:CGSizeMake(view.frame.size.width, view.frame.size.height)]; // YFEmitterSnowCell *emitterCell=[YFEmitterSnowCell snowCellWithCellImg:cellImg andRadious:radious andVelocity:20 andDirection:direction]; snowLayer.emitterCells=@[emitterCell]; } +(void)addSnowLayerInView:(UIView *)view { NSLog(@" - addSnowLayerInView"); //view,,,, [YFEmitterCustomLayer snowLayerInView:view atPosition:CGPointMake(-60,-20) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:19 andCellImg:nil]; [YFEmitterCustomLayer snowLayerInView:view atPosition:CGPointMake(-60,-20) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:9 andCellImg:nil]; [YFEmitterCustomLayer snowLayerInView:view atPosition:CGPointMake(-60,view.frame.size.height*0.33) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:14 andCellImg:nil]; } #pragma mark +(void)rainLayerInView:(UIView *)view atPosition:(CGPoint)position andDirection:(YFEmitterParticleCellDirection)direction andRadious:(CGFloat)radious andCellImg:(NSString *)cellImg { //layer YFEmitterCustomLayer *rainLayer=[self addCustomLayerInView:view atPosition:position inSize:CGSizeMake(view.frame.size.width, view.frame.size.height)]; rainLayer.emitterPosition = CGPointMake(320 / 2.0, -30); rainLayer.emitterSize = CGSizeMake(320 * 2.0, 0); rainLayer.emitterMode = kCAEmitterLayerOutline; rainLayer.emitterShape = kCAEmitterLayerLine; rainLayer.shadowOpacity = 1.0; rainLayer.shadowRadius = 0.0; rainLayer.shadowOffset = CGSizeMake(0.0, 1.0); rainLayer.shadowColor = [[UIColor whiteColor] CGColor]; rainLayer.seed = (arc4random()%100)+1; // YFEmitterRainCell *emitterCell = [YFEmitterRainCell rainCellWithCellImg:cellImg andRadious:radious andVelocity:20 andDirection:direction]; // emitterCell.contents = (id)[image CGImage]; emitterCell.color = [[UIColor colorWithRed:0.600 green:0.658 blue:0.743 alpha:1.000] CGColor]; rainLayer.emitterCells=@[emitterCell]; } + (void)addRainLayerInView:(UIView *)view { [YFEmitterCustomLayer rainLayerInView:view atPosition:CGPointMake(160,120) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:19 andCellImg:nil]; [YFEmitterCustomLayer rainLayerInView:view atPosition:CGPointMake(-60,-20) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:9 andCellImg:nil]; [YFEmitterCustomLayer rainLayerInView:view atPosition:CGPointMake(-60,view.frame.size.height*0.33) andDirection:YFEmitterParticleCellDirectionToBottom andRadious:14 andCellImg:nil]; } - (void)dealloc{ NSLog(@""); } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/EmitterLayer/YFEmitterCustomLayer.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,332
```objective-c // // YFEmitterRainCell.m // BigShow1949 // // Created by on 15-9-4. // #import "YFEmitterRainCell.h" @implementation YFEmitterRainCell +(instancetype)rainCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction { NSString * const rainPic = @"rain.png";// YFEmitterRainCell *cell=(YFEmitterRainCell *)[[self alloc] init]; cell.name = @"rain"; cell.birthRate = 40.0; cell.lifetime = 120.0; cell.velocity = 70; // falling down slowly cell.velocityRange = 3; cell.yAcceleration = 2; cell.emissionRange = 0.5 * M_PI; // some variation in angle cell.spinRange = 0.25 * M_PI; // slow spin // UIImage *img; if (cellImg.length==0) { img = [UIImage imageNamed:rainPic]; // UIColor *color = [UIColor colorWithRed:0.600 green:0.658 blue:0.743 alpha:1.000]; // img = [self imageWithColor:color]; }else{ img=[UIImage imageNamed:cellImg]; } // // img=[UIImage image:img scaleToSize:CGSizeMake(radious, radious)]; img=[UIImage image:img scaleToSize:CGSizeMake(1, 50)]; cell.contents = (id)[img CGImage]; // cell.velocity = radious*2; //,y,x,, cell.yAcceleration = 4; // cell.emissionRange = 0.5* M_PI; return cell; } + (UIImage*)imageWithColor:(UIColor*)color { CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f); UIGraphicsBeginImageContext(rect.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [color CGColor]); CGContextFillRect(context, rect); UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return theImage; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/RainCell/YFEmitterRainCell.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
526
```objective-c // // YFAnimationManager.h // YFAnimationStyle // // Created by ykh on 15/5/28. // #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> // typedef enum{ YFAnimationStyleOfSnow, // YFAnimationStyleOfLeaves, // YFAnimationStyleOfRain, // } YFAnimationStyle; @interface YFAnimationManager : NSObject +(instancetype)shareInstancetype; /** * viewstyle * * @param superView View * @param YFAnimationStyle */ -(void)showAnimationInView:(UIView *)superView withAnimationStyle:(YFAnimationStyle)YFAnimationStyle; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationManager/YFAnimationManager.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
158
```objective-c // // YFRainCell.h // BigShow1949 // // Created by on 15-9-4. // #import <QuartzCore/QuartzCore.h> #import <UIKit/UIKit.h> #import "YFPublicParticleCell.h" #import "UIImage+Extension.h" @interface YFEmitterRainCell : YFPublicParticleCell /** * ,,, * * @param cellImg * @param radious * @param velocity * * @return */ + (instancetype)rainCellWithCellImg:(NSString *)cellImg andRadious:(CGFloat)radious andVelocity:(CGFloat)velocity andDirection:(YFEmitterParticleCellDirection)direction; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationStyle/YFAnimationEmitterStyle/RainCell/YFEmitterRainCell.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
153
```objective-c // // YFAnimationManager.m // YFAnimationStyle // // Created by ykh on 15/5/28. // #import "YFAnimationManager.h" #import "YFEmitterCustomLayer.h" @implementation YFAnimationManager static id manager; +(instancetype)shareInstancetype{ YFAnimationManager *animationManager=[[YFAnimationManager alloc] init]; return animationManager; } -(void)showAnimationInView:(UIView *)superView withAnimationStyle:(YFAnimationStyle)YFAnimationStyle{ switch (YFAnimationStyle) { case YFAnimationStyleOfSnow: [YFEmitterCustomLayer addSnowLayerInView:superView]; break; case YFAnimationStyleOfLeaves: [YFEmitterCustomLayer addleavesLayerInView:superView]; break; case YFAnimationStyleOfRain: [YFEmitterCustomLayer addRainLayerInView:superView]; default: break; } } +(instancetype)allocWithZone:(struct _NSZone *)zone{ static dispatch_once_t onceToke; dispatch_once(&onceToke, ^{ if (manager == nil) { manager = [super allocWithZone:zone]; } }); return manager; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/02 - 粒子发射器/01 - Snow/YFAnimationManager/YFAnimationManager.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
276
```objective-c // // YFPopMenuViewController.h // BigShow1949 // // Created by on 15-9-4. // #import <UIKit/UIKit.h> @interface YFPopMenuViewController : BaseTableViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/YFPopMenuViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
52
```objective-c // // YFPopMenuViewController.m // BigShow1949 // // Created by on 15-9-4. // #import "YFPopMenuViewController.h" @implementation YFPopMenuViewController - (void)viewDidLoad { [super viewDidLoad]; [self setupDataArr:@[@[@"",@"YFContextMenuViewController"], @[@"5",@"YFAnimationVC02"], @[@"",@"YFAnimationVC03"], @[@"",@"YFAnimationVC04"], @[@"",@"YFAnimationVC05"], @[@"",@"YFAnimationVC06"], @[@"",@"YFShakeMenuViewController"],]]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/YFPopMenuViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
141
```objective-c // // YFAnimationVC05.m // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import "YFAnimationVC05.h" #import "YFPopOutMenu.h" @interface YFAnimationVC05 ()<YFPopoutMenuDelegate> @property (strong, nonatomic) IBOutlet UIImageView *imageView; @property (nonatomic) YFPopoutMenu * popMenu; @end @implementation YFAnimationVC05 - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; CAShapeLayer * circleLayer = [CAShapeLayer layer]; [circleLayer setPosition:CGPointMake(self.imageView.bounds.size.width/2, self.imageView.bounds.size.height/2)]; [circleLayer setBounds:self.imageView.bounds]; UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:self.imageView.bounds]; [circleLayer setPath:path.CGPath]; self.imageView.layer.mask = circleLayer; NSMutableArray * items = [NSMutableArray new]; for (int i =0; i<6; i++) { YFPopoutMenuItem * item = [[YFPopoutMenuItem alloc]initWithTitle:[NSString stringWithFormat:@"item%d",i] image:[UIImage imageNamed:[NSString stringWithFormat:@"pic%d",i]]]; [items addObject:item]; } self.popMenu = [[YFPopoutMenu alloc]initWithTitle:@"Test Title I want to test the auto break title" message:@"test message: this is a test message for the popout menu test test test..." items:items]; self.popMenu.delegate = self; } -(void)menu:(YFPopoutMenu *)menu willDismissWithSeleYFedItemAtIndex:(NSUInteger)index{ NSLog(@"menu dismiss with index %ld",index); } -(void)menuwillDismiss:(YFPopoutMenu *)menu{ NSLog(@"menu dismiss"); } - (IBAction)showList:(id)sender { self.popMenu.menuStyle = MenuStyleList; [self.popMenu showMenuInParentViewController:self withCenter:self.view.center]; } - (IBAction)showDefault:(id)sender { self.popMenu.menuStyle = MenuStyleDefault; [self.popMenu showMenuInParentViewController:self withCenter:self.view.center]; [self.popMenu.activityIndicator startAnimating]; } - (IBAction)showOval:(id)sender { self.popMenu.menuStyle = MenuStyleOval; [self.popMenu showMenuInParentViewController:self withCenter:self.view.center]; [self.popMenu.activityIndicator startAnimating]; } - (IBAction)showGrid:(id)sender { self.popMenu.menuStyle = MenuStyleGrid; [self.popMenu showMenuInParentViewController:self withCenter:self.view.center]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/05 - PopOutMenu/YFAnimationVC05.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
583
```objective-c // // YFPopOutMenu.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> #import <Foundation/Foundation.h> @class YFPopoutMenu; typedef enum : NSUInteger { MenuStyleDefault, MenuStyleList, MenuStyleOval, MenuStyleGrid, } PopoutMenuStyle; @interface YFPopoutMenuItem : NSObject @property (nonatomic,readonly) NSString * title; @property (nonatomic,readonly) UIImage * image; @property (nonatomic) UIColor * tintColor, * backgroundColor; //default tintColor is whiteColor //default backgroundColor is clearColor @property (nonatomic) NSTextAlignment textAligment; //default textAligment is NSTextAligmentCenter @property (nonatomic) UIFont * font; //defaut font is system font with size 14 -(instancetype)initWithTitle:(NSString*)title image:(UIImage*)image; @end @protocol YFPopoutMenuDelegate <NSObject> -(void)menu:(YFPopoutMenu*)menu willDismissWithSelectedItemAtIndex:(NSUInteger)index; -(void)menuwillDismiss:(YFPopoutMenu *)menu ; @end @interface YFPopoutMenu : UIViewController @property (nonatomic,readonly) NSString * titleText, * messageText; //the title and message of the menu @property (nonatomic)UIFont * titleFont, * messageFont; //the font of title and message @property (nonatomic)NSTextAlignment textAligment; //default is NSTextAligmentCenter @property (nonatomic,readonly) NSArray * items; //the buttons of the menu @property (nonatomic,readonly) UIView * menuView; //the menuView of the PopoutMenu @property (nonatomic) UIActivityIndicatorView * activityIndicator; //AYFivityIndicatorView of menuView default style is UIAYFivityIndicatorViewStyleWhite @property (nonatomic) UIColor * backgroundColor, * highlightColor, *tintColor; //backgroundColor of menuView, the default color is black with alpha 0.75 //highlightColor of items, the default color is white with alpha 0.5 @property (nonatomic) CGColorRef borderColor; //borderColor of menuView, default color is white @property (nonatomic) CGFloat blurLevel, borderRadius, borderWidth; //blurRadius of backgroundView, default value is 3.5(0~4) //borderRadius of menuView, default is 5 @property (nonatomic) PopoutMenuStyle menuStyle; @property (nonatomic) id<YFPopoutMenuDelegate>delegate; -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message items:(NSArray *)items; -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message images:(NSArray *)images; -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message itemTitles:(NSArray *)itemTitles; -(void)showMenuInParentViewController:(UIViewController*)parentVC withCenter:(CGPoint)center; -(void)dismissMenu; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/05 - PopOutMenu/YFPopOutMenu.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
617
```objective-c // // YFAnimationVC05.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> @interface YFAnimationVC05 : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/05 - PopOutMenu/YFAnimationVC05.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
53
```objective-c // // YFAnimationVC02.m // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import "YFAnimationVC02.h" #import "YFRotateCircleMenuVC.h" @interface YFAnimationVC02 () @property (nonatomic, strong) YFRotateCircleMenuVC *viewController; @end @implementation YFAnimationVC02 - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor redColor]; self.title = @"5"; YFRotateCircleMenuVC *viewController = [[YFRotateCircleMenuVC alloc] init]; [self.view addSubview:viewController.view]; [self addChildViewController:viewController]; [viewController didMoveToParentViewController:self]; self.viewController = viewController; } - (void)dealloc { [_viewController.view removeFromSuperview]; [_viewController removeFromParentViewController]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/YFAnimationVC02.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
278
```objective-c // // YFAnimationVC02.h // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> @interface YFAnimationVC02 : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/YFAnimationVC02.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
53
```objective-c // // YFRotateCircleMenuVC.h // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> @interface YFRotateCircleMenuVC : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/RotateMenuViewController/YFRotateCircleMenuVC.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
55
```objective-c // // YFItemView.h // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> @protocol YFItemViewDelegate <NSObject> - (void)didTapped:(NSInteger)tag; @end @interface YFItemView : UIButton @property (nonatomic, weak) id <YFItemViewDelegate>delegate; - (instancetype)initWithNormalImage:(NSString *)normal highlightedImage:(NSString *)highlighted tag:(NSInteger)tag title:(NSString *)title; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/RotateMenuViewController/YFItemView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
116
```objective-c // // YFItemView.m // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import "YFItemView.h" // ============== YFItemView ====================== // @interface YFItemView () @property (nonatomic, strong) NSString *normal; @property (nonatomic, strong) NSString *highlighted_; @property (nonatomic, assign) NSInteger tag_; @property (nonatomic, strong) NSString *title; @end @implementation YFItemView - (instancetype)initWithNormalImage:(NSString *)normal highlightedImage:(NSString *)highlighted tag:(NSInteger)tag title:(NSString *)title { self = [super init]; if (self) { _normal = normal; _highlighted_ = highlighted; _tag_ = tag; _title = title; [self configViews]; } return self; } #pragma mark - configViews - (void)configViews { self.tag = _tag_; [self setBackgroundImage:[UIImage imageNamed:_normal] forState:UIControlStateNormal]; [self setBackgroundImage:[UIImage imageNamed:_highlighted_] forState:UIControlStateHighlighted]; [self addTarget:self action:@selector(btnTapped:) forControlEvents:UIControlEventTouchUpInside]; [self setTitle:_title forState:UIControlStateNormal]; [self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; [self.titleLabel setFont:[UIFont systemFontOfSize:30.0]]; } - (void)btnTapped:(UIButton *)sender { if (self.delegate && [self.delegate respondsToSelector:@selector(didTapped:)]) { [self.delegate didTapped:sender.tag]; } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/RotateMenuViewController/YFItemView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
338
```objective-c // // YFRotateCircleMenuVC.m // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import "YFRotateCircleMenuVC.h" #import "YFItemView.h" #define RADIUS 100.0 #define PHOTONUM 5 #define TAGSTART 1000 #define TIME 1.5 #define SCALENUMBER 1.25 NSInteger array [PHOTONUM][PHOTONUM] = { {0,1,2,3,4}, {4,0,1,2,3}, {3,4,0,1,2}, {2,3,4,0,1}, {1,2,3,4,0} }; @interface YFRotateCircleMenuVC ()<YFItemViewDelegate> @property (nonatomic, assign) NSInteger currentTag; @end @implementation YFRotateCircleMenuVC CATransform3D rotationTransform1[PHOTONUM]; - (void)viewDidLoad { [super viewDidLoad]; [self configViews]; } #pragma mark - configViews - (void)configViews { self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"common_background"]]; NSArray *dataArray = @[@"exer_icon_biology", @"exer_icon_chemistry", @"exer_icon_chinese", @"exer_icon_english", @"exer_icon_geography"]; CGFloat centery = self.view.center.y - 50; CGFloat centerx = self.view.center.x; for (NSInteger i = 0;i < PHOTONUM;i++) { CGFloat tmpy = centery + RADIUS*cos(2.0*M_PI *i/PHOTONUM); CGFloat tmpx = centerx - RADIUS*sin(2.0*M_PI *i/PHOTONUM); YFItemView *view = [[YFItemView alloc] initWithNormalImage:dataArray[i] highlightedImage:[dataArray[i] stringByAppendingFormat:@"%@", @"_hover"] tag:TAGSTART+i title:nil]; view.frame = CGRectMake(0.0, 0.0,115,115); view.center = CGPointMake(tmpx,tmpy); view.delegate = self; rotationTransform1[i] = CATransform3DIdentity; CGFloat Scalenumber = fabs(i - PHOTONUM/2.0)/(PHOTONUM/2.0); // PHOTONUM/2.0 ? if (Scalenumber < 0.3) { Scalenumber = 0.4; } CATransform3D rotationTransform = CATransform3DIdentity; rotationTransform = CATransform3DScale (rotationTransform, Scalenumber*SCALENUMBER,Scalenumber*SCALENUMBER, 1); view.layer.transform=rotationTransform; [self.view addSubview:view]; } self.currentTag = TAGSTART; } #pragma mark - YFItemViewDelegate - (void)didTapped:(NSInteger)tag { if (self.currentTag == tag) { NSLog(@""); return; } // NSInteger t = [self getItemViewTag:tag]; for (NSInteger i = 0; i < PHOTONUM; i++ ) { UIView *view = [self.view viewWithTag:TAGSTART+i]; [view.layer addAnimation:[self moveanimation:TAGSTART+i number:t] forKey:@"position"]; [view.layer addAnimation:[self setscale:TAGSTART+i clicktag:tag] forKey:@"transform"]; NSInteger j = array[tag - TAGSTART][i]; CGFloat Scalenumber = fabs(j - PHOTONUM/2.0)/(PHOTONUM/2.0); if (Scalenumber < 0.3) { Scalenumber = 0.4; } } self.currentTag = tag; } - (CAAnimation*)setscale:(NSInteger)tag clicktag:(NSInteger)clicktag { NSInteger i = array[clicktag - TAGSTART][tag - TAGSTART]; NSInteger i1 = array[self.currentTag - TAGSTART][tag - TAGSTART]; CGFloat Scalenumber = fabs(i - PHOTONUM/2.0)/(PHOTONUM/2.0); CGFloat Scalenumber1 = fabs(i1 - PHOTONUM/2.0)/(PHOTONUM/2.0); if (Scalenumber < 0.3) { Scalenumber = 0.4; } CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"transform"]; animation.duration = TIME; animation.repeatCount =1; CATransform3D dtmp = CATransform3DScale(rotationTransform1[tag - TAGSTART],Scalenumber*SCALENUMBER, Scalenumber*SCALENUMBER, 1.0); animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DScale(rotationTransform1[tag - TAGSTART],Scalenumber1*SCALENUMBER,Scalenumber1*SCALENUMBER, 1.0)]; animation.toValue = [NSValue valueWithCATransform3D:dtmp ]; animation.autoreverses = NO; animation.removedOnCompletion = NO; animation.fillMode = kCAFillModeForwards; return animation; } - (CAAnimation*)moveanimation:(NSInteger)tag number:(NSInteger)num { // 1000 4 // CALayer UIView *view = [self.view viewWithTag:tag]; CAKeyframeAnimation *animation = [CAKeyframeAnimation animation]; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL,view.layer.position.x,view.layer.position.y); NSInteger p = [self getItemViewTag:tag]; CGFloat f = 2.0*M_PI - 2.0*M_PI *p/PHOTONUM; CGFloat h = f + 2.0*M_PI *num/PHOTONUM; CGFloat centery = self.view.center.y - 50; CGFloat centerx = self.view.center.x; CGFloat tmpy = centery + RADIUS*cos(h); CGFloat tmpx = centerx - RADIUS*sin(h); view.center = CGPointMake(tmpx,tmpy); CGPathAddArc(path,nil,self.view.center.x, self.view.center.y - 50,RADIUS,f+ M_PI/2,f+ M_PI/2 + 2.0*M_PI *num/PHOTONUM,0); animation.path = path; CGPathRelease(path); animation.duration = TIME; animation.repeatCount = 1; animation.calculationMode = @"paced"; return animation; } - (NSInteger)getItemViewTag:(NSInteger)tag { NSLog(@"getItemViewTag=== self.currentTag == %d, tag == %d", self.currentTag, tag); if (self.currentTag >tag){ // NSLog(@"if = %d", self.currentTag - tag); return self.currentTag - tag; } else { // NSLog(@"else = %d", self.currentTag - tag); return PHOTONUM - tag + self.currentTag ; } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/02 - 5RotateMenu/RotateMenuViewController/YFRotateCircleMenuVC.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,572
```objective-c // // XRPopMenuView.h // MatchBox // view // Created by XiRuo on 15/7/22. // #import <UIKit/UIKit.h> typedef void (^XRPopMenuViewSelectedBlock)(void); @interface XRPopMenuView : UIView<UIGestureRecognizerDelegate> @property (nonatomic, readonly)UIImageView *backgroundImgView; /** * */ - (void)addMenuItemWithTitle:(NSString*)title andIcon:(UIImage*)icon andSelectedBlock:(XRPopMenuViewSelectedBlock)block; /** * */ - (void)show; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/07 - 抖动菜单/XRPopMenuView.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
122
```objective-c // // YFPopOutMenu.m // BigShow1949 // // Created by WangMengqi on 15/9/2. // #define TRANSITION_DURATION 0.3 #define SCREENSHOT_QUALITY 0.75 #define FRAME_OFFSET 10 #import "YFPopOutMenu.h" #pragma mark Category @implementation UIView (ScreenShot) -(UIImage*)screenShot{ UIGraphicsBeginImageContext(self.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); [self.layer renderInContext:context]; UIImage * screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData * imageData = UIImageJPEGRepresentation(screenImage, SCREENSHOT_QUALITY); screenImage = [UIImage imageWithData:imageData]; return screenImage; } -(UIImage*)screenShotOnScrolViewWithContentOffset:(CGPoint)offset{ UIGraphicsBeginImageContext(self.bounds.size); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(context, -offset.x, -offset.y); [self.layer renderInContext:context]; UIImage * screenImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); NSData * imageData = UIImageJPEGRepresentation(screenImage, SCREENSHOT_QUALITY); screenImage = [UIImage imageWithData:imageData]; return screenImage; } -(void)addTopBorderwithWidth:(CGFloat)width andColor:(CGColorRef)borderColor{ CALayer *upperBorder = [CALayer layer]; upperBorder.backgroundColor = borderColor; upperBorder.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), width); [self.layer addSublayer:upperBorder]; } @end @implementation UIImage (Blur_and_Color_Filter) -(UIImage*)blurWithRadius:(CGFloat)radius{ radius =(radius<0)?0:radius; radius =(radius>4)?4:radius; CIImage * inputImage = [CIImage imageWithCGImage:self.CGImage]; CIFilter * blurFilter = [CIFilter filterWithName:@"CIGaussianBlur"]; [blurFilter setValue:inputImage forKey:@"inputImage"]; [blurFilter setValue:[NSNumber numberWithFloat:radius] forKey:@"inputRadius"]; CIImage * outputImage = [blurFilter outputImage]; outputImage = [outputImage imageByCroppingToRect:[inputImage extent]]; UIImage * blurImage = [UIImage imageWithCIImage:outputImage]; return blurImage; } @end #pragma mark YFPopoutMenuItem @implementation YFPopoutMenuItem -(instancetype)init{ NSAssert(NO, @"Can't create with init"); return nil; } -(instancetype)initWithTitle:(NSString *)title image:(UIImage *)image{ if (self = [super init]) { _title = title; _image = image; self.font = [UIFont systemFontOfSize:14]; self.textAligment = NSTextAlignmentCenter; self.tintColor = [UIColor whiteColor]; self.backgroundColor = [UIColor clearColor]; } return self; } @end #pragma mark YFPopoutMenuItemView @interface YFPopoutMenuItemView : UIView @property (nonatomic)UILabel * titleLabel; @property (nonatomic)UIImage * image; @property (nonatomic)UIImageView * iconIamageView; @property (nonatomic)PopoutMenuStyle menuStyle; @end @implementation YFPopoutMenuItemView -(instancetype)initWithMenuItem:(YFPopoutMenuItem*)item frame:(CGRect)frame menuStyle:(PopoutMenuStyle)menuStyle{ if (self = [super init]) { self.menuStyle = menuStyle; self.backgroundColor = item.backgroundColor; if (item.title!=nil) { self.titleLabel = [UILabel new]; [self.titleLabel setTextColor:item.tintColor]; [self.titleLabel setTextAlignment:item.textAligment]; self.titleLabel.backgroundColor = [UIColor clearColor]; [self.titleLabel setText:item.title]; [self.titleLabel setFont:item.font]; [self addSubview:self.titleLabel]; } if (item.image!=nil) { self.image = [item.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; self.iconIamageView = [UIImageView new]; self.iconIamageView.image = self.image; [self.iconIamageView setTintColor:item.tintColor]; self.iconIamageView.backgroundColor = [UIColor clearColor]; [self.iconIamageView setContentMode:UIViewContentModeScaleAspectFit]; [self addSubview:self.iconIamageView]; } self.frame = frame; } return self; } -(void)layoutSubviews{ switch (self.menuStyle) { case MenuStyleDefault: [self layoutMenuItemViewasDefault]; break; case MenuStyleList: [self layoutMenuItemViewasList]; break; case MenuStyleOval: [self layoutMenuItemViewasOval]; break; case MenuStyleGrid: [self layoutMenuItemViewasGrid]; break; } } -(void)layoutMenuItemViewasDefault{ CGSize imageSize; if (self.iconIamageView!= nil) { imageSize = CGSizeMake(self.bounds.size.height*0.9, self.bounds.size.height*0.9); self.iconIamageView.frame = CGRectMake(self.bounds.size.width*0.05, self.bounds.size.height*0.05, imageSize.width, imageSize.height); }else{ imageSize = CGSizeMake(0, 0); } CGSize labelSize; if (self.titleLabel!=nil) { labelSize = CGSizeMake((self.bounds.size.width*0.9 - imageSize.width), self.bounds.size.height*0.9); self.titleLabel.frame = CGRectMake(CGRectGetMaxX(self.iconIamageView.frame), self.bounds.size.height*0.05, labelSize.width, labelSize.height); }else{ labelSize = CGSizeMake(0, 0); } if (self.iconIamageView == nil) { self.titleLabel.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); } if (self.titleLabel == nil) { self.iconIamageView.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); } } -(void)layoutMenuItemViewasList{ [self layoutMenuItemViewasDefault]; } -(void)layoutMenuItemViewasOval{ CGSize labelSize; if (self.titleLabel!= nil) { labelSize = [self.titleLabel sizeThatFits:(CGSize){self.bounds.size.width*0.9,CGFLOAT_MAX}]; }else{ labelSize = CGSizeMake(0, 0); } labelSize.width = self.bounds.size.width*0.9; CGSize imageSize; if (self.iconIamageView!=nil) { imageSize = CGSizeMake(self.bounds.size.width*0.7, self.bounds.size.height-labelSize.height-5); self.iconIamageView.frame = CGRectMake(self.bounds.size.width*0.15, self.bounds.size.height*0.05, imageSize.width, imageSize.height); self.titleLabel.frame = CGRectMake(self.bounds.size.width*0.05, CGRectGetMaxY(self.iconIamageView.frame), labelSize.width, labelSize.height); }else{ self.iconIamageView = nil; self.titleLabel.frame = CGRectMake(self.bounds.size.width*0.05, CGRectGetMaxY(self.iconIamageView.frame), labelSize.width, labelSize.height); self.titleLabel.center = CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2); } } -(void)layoutMenuItemViewasGrid{ [self layoutMenuItemViewasOval]; } -(void)dealloc{ // NSLog(@"%@ has been dealloc",self.titleLabel.text); } @end #pragma mark YFPopoutMenu @interface YFPopoutMenu () @property (nonatomic)UIImageView * blurView; @property (nonatomic)CGPoint menuCenter; @property (nonatomic)NSMutableArray * itemViews; @property (nonatomic)UITextView * messageView, * titleView; @property (nonatomic)YFPopoutMenuItemView * selectedItemView; @property (nonatomic)YFPopoutMenuItem * selectedItem; @end @implementation YFPopoutMenu #pragma mark -LifeCycle -(instancetype)init{ NSAssert(NO, @"Can't create with init"); return nil; } -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message items:(NSArray *)items{ if (self = [super init]) { _items = items; _titleText = title; _messageText = message; _menuView = [UIView new]; self.textAligment = NSTextAlignmentCenter; self.activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge]; self.titleFont = [UIFont systemFontOfSize:[UIFont systemFontSize]+3]; self.messageFont = [UIFont systemFontOfSize:[UIFont systemFontSize]]; self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.85]; self.tintColor = [UIColor whiteColor]; self.highlightColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.5]; self.borderColor = [UIColor whiteColor].CGColor; self.borderWidth = 2; self.borderRadius = 5; self.blurLevel = 3.5; self.menuStyle = MenuStyleDefault; } return self; } -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message images:(NSArray *)images{ NSMutableArray * items = [NSMutableArray new]; [images enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { YFPopoutMenuItem * item = [[YFPopoutMenuItem alloc]initWithTitle:nil image:(UIImage*)obj]; [items addObject:item]; }]; return [self initWithTitle:title message:message items:items]; } -(instancetype)initWithTitle:(NSString *)title message:(NSString *)message itemTitles:(NSArray *)itemTitles{ NSMutableArray * items = [NSMutableArray new]; [itemTitles enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { YFPopoutMenuItem * item = [[YFPopoutMenuItem alloc]initWithTitle:(NSString*)obj image:nil]; [items addObject:item]; }]; return [self initWithTitle:title message:message items:items]; } #pragma mark -Private -(void)YF_addToParentVC:(UIViewController*)parentVC withAnimation:(BOOL)animate{ [parentVC addChildViewController:self]; [parentVC.view addSubview:self.view]; } -(void)YF_removeFromParentVCwithAnimation:(BOOL)animate{ self.menuView.transform = CGAffineTransformIdentity; [self removeFromParentViewController]; [self.view removeFromSuperview]; [self.blurView removeFromSuperview]; self.blurView = nil; } -(CGPoint)YF_centroidOfTouches:(NSSet*)touches inVeiw:(UIView*)view{ CGFloat sumX; CGFloat sumY; for (UITouch * touch in touches) { CGPoint loc = [touch locationInView:view]; sumX += loc.x; sumY += loc.y; } return CGPointMake(sumX/[touches count], sumY/[touches count]); } -(YFPopoutMenuItemView*)itemViewatPoint:(CGPoint)point{ YFPopoutMenuItemView * selectedItemView = nil; YFPopoutMenuItem * selectedItem = nil; if (CGRectContainsPoint(self.menuView.frame, point)) { point = [self.view convertPoint:point toView:self.menuView]; selectedItemView = [self.itemViews filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(YFPopoutMenuItemView * itemView, NSDictionary *bindings) { return CGRectContainsPoint(itemView.frame, point); }]].lastObject; } if (selectedItemView!=nil) { selectedItem = [self.items objectAtIndex:[self.itemViews indexOfObject:selectedItemView]]; selectedItemView.backgroundColor = self.highlightColor; if (self.selectedItemView != selectedItemView) { self.selectedItemView.backgroundColor = self.selectedItem.backgroundColor; self.selectedItemView = selectedItemView; self.selectedItem = selectedItem; } }else{ self.selectedItemView.backgroundColor = self.selectedItem.backgroundColor; self.selectedItemView = nil; self.selectedItem = nil; } return selectedItemView; } #pragma mark -Animation -(void)showMenuInParentViewController:(UIViewController *)parentVC withCenter:(CGPoint)center{ [self YF_addToParentVC:parentVC withAnimation:YES]; self.menuCenter = center; self.view.frame = parentVC.view.bounds; self.blurView = [[UIImageView alloc]init]; [self.view addSubview:self.blurView]; [self createScreenshotwithComleteAYFion:^{ [self layoutMenuView]; }]; } -(void)dismissMenu{ [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.75 options:0 animations:^{ if (self.menuView.superview!=nil) { self.menuView.transform = CGAffineTransformMakeScale(0.1, 0.1); } } completion:^(BOOL finished) { [self YF_removeFromParentVCwithAnimation:YES]; }]; } -(void)createScreenshotwithComleteAYFion:(dispatch_block_t)completeAYFion{ self.blurView.frame = self.view.bounds; self.blurView.alpha = 0.0; self.menuView.alpha = 0.0; UIImage * screenshot = nil; if ([self.parentViewController.view isKindOfClass:[UIScrollView class]]) { screenshot = [self.parentViewController.view screenShotOnScrolViewWithContentOffset:[(UIScrollView*)self.parentViewController.view contentOffset]]; }else{ screenshot = [self.parentViewController.view screenShot]; } self.blurView.alpha = 1.0; self.menuView.alpha = 1.0; if (self.blurLevel >0.0) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage * blurImage = [screenshot blurWithRadius:self.blurLevel]; dispatch_async(dispatch_get_main_queue(), ^{ CATransition * transition = [CATransition animation]; transition.duration = TRANSITION_DURATION; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionFade; self.blurView.image = blurImage; [self.blurView.layer addAnimation:transition forKey:@"showBlurView"]; [self.view setNeedsLayout]; if (completeAYFion != nil) { completeAYFion(); } [self.view setNeedsLayout]; [self.view layoutIfNeeded]; }); }); }else{ self.blurView.image = screenshot; if (completeAYFion != nil) { completeAYFion(); } } } #pragma mark -Layout -(void)layoutMenuView{ self.itemViews = [NSMutableArray new]; self.menuView.backgroundColor = _backgroundColor; self.menuView.layer.borderWidth = self.borderWidth; self.menuView.layer.borderColor = self.borderColor; self.menuView.layer.cornerRadius = self.borderRadius; self.menuView.layer.masksToBounds = YES; self.titleView = [UITextView new]; self.titleView.userInteractionEnabled = NO; self.titleView.backgroundColor = [UIColor clearColor]; [self.titleView setTextAlignment:self.textAligment]; [self.titleView setTextColor:self.tintColor]; [self.titleView setText:self.titleText]; [self.titleView setFont:self.titleFont]; self.messageView = [UITextView new]; self.messageView.userInteractionEnabled = NO; self.messageView.backgroundColor = [UIColor clearColor]; [self.messageView setTextAlignment:self.textAligment]; [self.messageView setTextColor:self.tintColor]; [self.messageView setText:self.messageText]; [self.messageView setFont:self.messageFont]; switch (self.menuStyle) { case MenuStyleList: [self layoutasList]; break; case MenuStyleOval: [self layoutasOval]; break; case MenuStyleGrid: [self layoutasGrid]; break; default: [self layoutasDefault]; break; } [self.view addSubview:self.menuView]; self.menuView.transform = CGAffineTransformMakeScale(0.1, 0.1); [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.75 options:0 animations:^{ self.menuView.transform = CGAffineTransformMakeScale(1, 1); } completion:^(BOOL finished) { self.menuView.transform = CGAffineTransformMakeScale(1, 1); self.activityIndicator.center = CGPointMake(self.menuView.bounds.size.width/2, self.menuView.bounds.size.height/2); [self.menuView addSubview:self.activityIndicator]; }]; } -(void)layoutasDefault{ CGFloat menuWidth = (self.view.bounds.size.width<self.view.bounds.size.height)?self.view.bounds.size.width*0.8:self.view.bounds.size.height*0.8; [self layoutTitleandMessagewithMenuWidth:menuWidth]; CGFloat offSetY = CGRectGetMaxY(self.messageView.frame)+FRAME_OFFSET; NSInteger colCount = ceilf(sqrtf([self.items count])); NSInteger rowCount = ceilf([self.items count]/(CGFloat)colCount); CGFloat itemWidth = menuWidth/colCount; CGSize itemSize = CGSizeMake(itemWidth, 40); [self.items enumerateObjectsUsingBlock:^(YFPopoutMenuItem * obj, NSUInteger idx, BOOL *stop) { NSUInteger index = idx; while (index >= colCount) { index -= colCount; } NSUInteger rowIndex = floorf((CGFloat)idx/colCount); YFPopoutMenuItemView * itemView = nil; if (idx >= [self.items count]-([self.items count]%colCount)) { CGFloat rowLength = [self.items count]%colCount*itemSize.width; CGFloat offSetX = (menuWidth - rowLength)/2; itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(offSetX+index*itemSize.width, offSetY+rowIndex*itemSize.height, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; }else{ itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(index*itemSize.width, offSetY+rowIndex*itemSize.height, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; } [self.menuView addSubview:itemView]; [self.itemViews addObject:itemView]; }]; self.menuView.frame = [self menuFramewithWidth:menuWidth Height:offSetY + rowCount*itemSize.height+FRAME_OFFSET Center:self.menuCenter]; [self.menuView addSubview:self.titleView]; [self.menuView addSubview:self.messageView]; } -(void)layoutasList{ CGFloat menuWidth = (self.view.bounds.size.width<self.view.bounds.size.height)?self.view.bounds.size.width*0.75:self.view.bounds.size.height*0.75; [self layoutTitleandMessagewithMenuWidth:menuWidth]; CGSize itemSize = CGSizeMake(menuWidth*0.8, 45); CGFloat offSetY = CGRectGetMaxY(self.messageView.frame)+FRAME_OFFSET; CGFloat offSetX = menuWidth * 0.1; [self.items enumerateObjectsUsingBlock:^(YFPopoutMenuItem*obj, NSUInteger idx, BOOL *stop) { YFPopoutMenuItemView * itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(offSetX, offSetY+idx*itemSize.height, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; [itemView addTopBorderwithWidth:self.borderWidth/4 andColor:self.borderColor]; [self.menuView addSubview:itemView]; [self.itemViews addObject:itemView]; }]; self.menuView.frame = [self menuFramewithWidth:menuWidth Height:offSetY+self.items.count*itemSize.height Center:self.menuCenter]; [self.menuView addSubview:self.titleView]; [self.menuView addSubview:self.messageView]; } -(void)layoutasOval{ CGFloat menuWidth = (self.view.bounds.size.width<self.view.bounds.size.height)?self.view.bounds.size.width*0.9:self.view.bounds.size.height*0.9; CGFloat radius = menuWidth*0.8/2; [self layoutTitleandMessagewithMenuWidth:menuWidth]; CGSize itemSize = CGSizeMake(menuWidth*0.2, menuWidth*0.2); CGFloat identicalAngle = 2*M_PI / [self.items count]; self.menuView.frame = [self menuFramewithWidth:menuWidth Height:menuWidth Center:self.menuCenter]; CGPoint center = CGPointMake(self.menuView.bounds.size.width/2, self.menuView.bounds.size.height/2); self.menuView.layer.borderWidth = 0; CAShapeLayer * circleLayer = [CAShapeLayer new]; [circleLayer setPosition:center]; [circleLayer setBounds:self.menuView.bounds]; UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:self.menuView.bounds]; [circleLayer setPath:path.CGPath]; self.menuView.layer.mask = circleLayer; [self.items enumerateObjectsUsingBlock:^(YFPopoutMenuItem * obj, NSUInteger idx, BOOL *stop) { CGFloat angle = idx*identicalAngle; YFPopoutMenuItemView * itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(0, 0, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; itemView.center = CGPointMake(center.x + cosf(angle)*radius, center.y + sinf(angle)*radius); [self.menuView addSubview:itemView]; [self.itemViews addObject:itemView]; }]; self.titleView.center = CGPointMake(self.menuView.bounds.size.width/2, self.menuView.bounds.size.height/2 - (self.titleView.bounds.size.height)/2); self.messageView.center = CGPointMake(self.menuView.bounds.size.width/2, self.menuView.bounds.size.height/2 + (self.messageView.bounds.size.height)/2); [self.menuView addSubview:self.titleView]; [self.menuView addSubview:self.messageView]; } -(void)layoutasGrid{ CGFloat menuWidth = (self.view.bounds.size.width<self.view.bounds.size.height)?self.view.bounds.size.width*0.75:self.view.bounds.size.height*0.75; [self layoutTitleandMessagewithMenuWidth:menuWidth]; CGFloat offSetY = CGRectGetMaxY(self.messageView.frame)+FRAME_OFFSET; NSInteger colCount = ceilf(sqrtf([self.items count])); NSInteger rowCount = ceilf([self.items count]/(CGFloat)colCount); CGFloat itemWidth = menuWidth/colCount; CGSize itemSize = CGSizeMake(itemWidth, itemWidth); [self.items enumerateObjectsUsingBlock:^(YFPopoutMenuItem * obj, NSUInteger idx, BOOL *stop) { NSUInteger index = idx; while (index >= colCount) { index -= colCount; } NSUInteger rowIndex = floorf((CGFloat)idx/colCount); YFPopoutMenuItemView * itemView = nil; if (idx >= [self.items count]-([self.items count]%colCount)) { CGFloat rowLength = [self.items count]%colCount*itemSize.width; CGFloat offSetX = (menuWidth - rowLength)/2; itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(offSetX+index*itemSize.width, offSetY+rowIndex*itemSize.height, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; }else{ itemView = [[YFPopoutMenuItemView alloc]initWithMenuItem:obj frame:CGRectMake(index*itemSize.width, offSetY+rowIndex*itemSize.height, itemSize.width, itemSize.height) menuStyle:self.menuStyle]; } [self.menuView addSubview:itemView]; [self.itemViews addObject:itemView]; }]; self.menuView.frame = [self menuFramewithWidth:menuWidth Height:offSetY + rowCount*itemSize.height+FRAME_OFFSET Center:self.menuCenter]; [self.menuView addSubview:self.titleView]; [self.menuView addSubview:self.messageView]; } -(void)layoutTitleandMessagewithMenuWidth:(CGFloat)menuWidth{ CGSize titleSize; CGSize messageSize; if (self.menuStyle == MenuStyleOval) { if (self.titleText != nil) { titleSize = [self.titleView sizeThatFits:(CGSize){menuWidth*0.55,CGFLOAT_MAX}]; titleSize.width = menuWidth*0.55; }else{ titleSize = CGSizeMake(0, 0); } if (self.messageText != nil) { messageSize = [self.messageView sizeThatFits:(CGSize){menuWidth*0.55,CGFLOAT_MAX}]; messageSize.width = menuWidth*0.55; }else{ messageSize = CGSizeMake(0, 0); } }else{ if (self.titleText != nil) { titleSize = [self.titleView sizeThatFits:(CGSize){menuWidth*0.9,CGFLOAT_MAX}]; titleSize.width = menuWidth*0.9; }else{ titleSize = CGSizeMake(0, 0); } if (self.messageText != nil) { messageSize = [self.messageView sizeThatFits:(CGSize){menuWidth*0.8,CGFLOAT_MAX}]; messageSize.width = menuWidth*0.8; }else{ messageSize = CGSizeMake(0, 0); } } self.titleView.scrollEnabled = NO; self.titleView.frame = CGRectMake(menuWidth*0.05, FRAME_OFFSET, titleSize.width, titleSize.height); self.messageView.scrollEnabled = NO; self.messageView.frame = CGRectMake(menuWidth*0.1, CGRectGetMaxY(self.titleView.frame)+FRAME_OFFSET, messageSize.width, messageSize.height); } -(CGRect)menuFramewithWidth:(CGFloat)width Height:(CGFloat)height Center:(CGPoint)center{ CGFloat originX = ((center.x-width/2)<0)?0:(center.x-width/2); originX = ((center.x-width/2)>(self.view.bounds.size.width-width))? (self.view.bounds.size.width-width):(originX); CGFloat originY = ((center.y-height/2)<0)?0:(center.y-height/2); originY = ((center.y-height/2)>(self.view.bounds.size.height-height))? (self.view.bounds.size.height-height):(originY); CGRect frame = CGRectMake(originX,originY,width,height); return frame; } #pragma mark -ViewController - (void)viewDidLoad { [super viewDidLoad]; NSNotificationCenter * defaultCenter=[NSNotificationCenter defaultCenter]; [defaultCenter addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]]; } -(void)viewWillLayoutSubviews{ [super viewWillLayoutSubviews]; } -(void)viewDidDisappear:(BOOL)animated{ [super viewDidDisappear:animated]; [self.activityIndicator stopAnimating]; [self.menuView.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [obj removeFromSuperview]; }]; self.menuView.layer.mask = nil; [self.view.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [obj removeFromSuperview]; }]; [self.itemViews removeAllObjects]; self.itemViews = nil; self.titleView = nil; self.messageView = nil; } -(void)dealloc{ } #pragma mark -Rotation - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskAll; } -(BOOL)shouldAutorotate{ return [self.parentViewController shouldAutorotate]; } -(void)OrientationDidChange:(NSNotification*)notification{ CGFloat newCenterX = self.menuCenter.y; CGFloat newCenterY = self.menuCenter.x; self.menuCenter = CGPointMake(newCenterX, newCenterY); } -(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ [super willAnimateRotationToInterfaceOrientation:toInterfaceOrientation duration:duration]; if (toInterfaceOrientation!= UIDeviceOrientationPortraitUpsideDown) { if ([self isViewLoaded] && self.view.window != nil) { [self createScreenshotwithComleteAYFion:^{ self.menuView.frame = [self menuFramewithWidth:self.menuView.bounds.size.width Height:self.menuView.bounds.size.height Center:self.menuCenter]; }]; } } } #pragma mark -Touch -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint point = [self YF_centroidOfTouches:touches inVeiw:self.view]; [self itemViewatPoint:point]; } -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint point = [self YF_centroidOfTouches:touches inVeiw:self.view]; [self itemViewatPoint:point]; } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{ CGPoint point = [self YF_centroidOfTouches:touches inVeiw:self.view]; [self itemViewatPoint:point]; if (self.selectedItemView != nil) { NSUInteger index = [self.itemViews indexOfObject:self.selectedItemView]; if ([self.delegate respondsToSelector:@selector(menu:willDismissWithSelectedItemAtIndex:)]) { [self.delegate menu:self willDismissWithSelectedItemAtIndex:index]; } [self dismissMenu]; }else{ if (!CGRectContainsPoint(self.menuView.frame, point)) { if ([self.delegate respondsToSelector:@selector(menuwillDismiss:)]) { [self.delegate menuwillDismiss:self]; } [self dismissMenu]; } } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/05 - PopOutMenu/YFPopOutMenu.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
6,376
```objective-c // // YFShakeMenuViewController.m // BigShow1949 // // Created by zhht01 on 16/1/21. // #import "YFShakeMenuViewController.h" #import "XRPopMenuView.h" @interface YFShakeMenuViewController () @end @implementation YFShakeMenuViewController - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; [self configButton]; } - (void)configButton { UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setFrame:CGRectMake(.0f, .0f, 80.0f, 40.0f)]; [button setTitle:@"" forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; button.center = self.view.center; [self.view addSubview:button]; [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside]; } - (void)buttonClick:(id)sender { [self showPopMenu]; } - (void)showPopMenu { XRPopMenuView *menuView = [[XRPopMenuView alloc] init]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"editButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"markButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"editButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"markButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"editButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView addMenuItemWithTitle:@"" andIcon:[UIImage imageNamed:@"markButton"] andSelectedBlock:^{ NSLog(@" selected"); }]; [menuView show]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/07 - 抖动菜单/YFShakeMenuViewController.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
417
```objective-c // // XRPopMenuView.m // MatchBox // // Created by XiRuo on 15/7/22. // #import "XRPopMenuView.h" #define XRPopMenuViewTag 1991 #define COLUMN_COUNT 3 //3() #define XRPopMenuViewImageHeight 70.0f #define XRPopMenuViewTitleHeight 15.0f #define XRPopMenuViewVerticalPadding 20.0f #define XRPopMenuViewHorizontalMargin 10.0f #define XRPopMenuViewImageAndTitleVerticalPadding 15.0f #define XRPopMenuViewRriseAnimationID @"XRPopMenuViewRriseAnimationID" #define XRPopMenuViewDismissAnimationID @"XRPopMenuViewDismissAnimationID" #define XRPopMenuViewAnimationTime 0.2f #define XRPopMenuViewAnimationInterval (XRPopMenuViewAnimationTime / 5) #define viewBackColor [UIColor colorWithRed:25/255.0f green:25/255.0f blue:25/255.0f alpha:0.95] #define kScreenWidth [UIScreen mainScreen].applicationFrame.size.width #define kScreenHeight [UIScreen mainScreen].applicationFrame.size.height #define WEAKSELF typeof(self) __weak weakSelf = self; #pragma mark - XRPopMenuItemButton @interface XRPopMenuItemButton : UIButton @property (nonatomic,copy) XRPopMenuViewSelectedBlock selectedBlock; @end @implementation XRPopMenuItemButton + (id)XRPopMenuItemButtonWithTitle:(NSString*)title andIcon:(UIImage*)icon andSelectedBlock:(XRPopMenuViewSelectedBlock)block { XRPopMenuItemButton *button = [XRPopMenuItemButton buttonWithType:UIButtonTypeCustom]; [button setImage:icon forState:UIControlStateNormal]; [button setTitle:title forState:UIControlStateNormal]; [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; button.titleLabel.textAlignment = NSTextAlignmentCenter; button.titleLabel.font = [UIFont boldSystemFontOfSize:12]; button.selectedBlock = block; return button; } - (void)layoutSubviews { [super layoutSubviews]; self.imageView.frame = CGRectMake(.0f, .0f, XRPopMenuViewImageHeight, XRPopMenuViewImageHeight); self.titleLabel.frame = CGRectMake(.0f, XRPopMenuViewImageHeight + XRPopMenuViewImageAndTitleVerticalPadding, XRPopMenuViewImageHeight, XRPopMenuViewTitleHeight); } @end #pragma mark - XRPopMenuView @interface XRPopMenuView() @property(nonatomic,copy) XRPopMenuViewSelectedBlock selectedBlock; @property(nonatomic,strong) UIImageView *backgroundView; @property(nonatomic,strong) NSMutableArray *buttons; @end @implementation XRPopMenuView #pragma mark - Init - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { UITapGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss:)]; ges.delegate = self; [self addGestureRecognizer:ges]; self.backgroundColor = [UIColor clearColor]; UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:self.bounds]; backgroundView.backgroundColor = viewBackColor; backgroundView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; [self addSubview:backgroundView]; self.backgroundView = backgroundView; self.buttons = [[NSMutableArray alloc] init]; } return self; } - (void)addMenuItemWithTitle:(NSString*)title andIcon:(UIImage*)icon andSelectedBlock:(XRPopMenuViewSelectedBlock)block { XRPopMenuItemButton *button = [XRPopMenuItemButton XRPopMenuItemButtonWithTitle:title andIcon:icon andSelectedBlock:block]; [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:button]; [self.buttons addObject:button]; } - (CGRect)frameForButtonAtIndex:(NSUInteger)index { NSUInteger columnIndex = index % COLUMN_COUNT; NSUInteger rowCount = self.buttons.count / COLUMN_COUNT + (self.buttons.count % COLUMN_COUNT > 0 ? 1 : 0); NSUInteger rowIndex = index / COLUMN_COUNT; CGFloat itemHeight = (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) * rowCount + (rowCount > 1 ? (rowCount - 1) * XRPopMenuViewHorizontalMargin : 0); NSInteger allButtonCount = self.buttons.count; NSInteger realRowCount = (allButtonCount <= 3) ? allButtonCount : 3; CGFloat offsetXPadding = (kScreenWidth - realRowCount * XRPopMenuViewImageHeight) / (realRowCount + 1); CGFloat offsetX = offsetXPadding; offsetX += (XRPopMenuViewImageHeight + offsetXPadding) * columnIndex; CGFloat offsetY = (CGRectGetHeight(self.frame) - itemHeight) / 2.0; offsetY += (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight + XRPopMenuViewVerticalPadding + XRPopMenuViewImageAndTitleVerticalPadding) * rowIndex; CGRect rect = CGRectMake(offsetX, offsetY, XRPopMenuViewImageHeight, (XRPopMenuViewImageHeight+XRPopMenuViewTitleHeight)); return rect; } - (void)layoutSubviews { [super layoutSubviews]; for (NSUInteger i = 0; i < self.buttons.count; i++) { XRPopMenuItemButton *button = self.buttons[i]; button.frame = [self frameForButtonAtIndex:i]; } } - (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer { if ([gestureRecognizer.view isKindOfClass:[XRPopMenuItemButton class]]) { return NO; } CGPoint location = [gestureRecognizer locationInView:self]; for (UIView* subview in self.buttons) { if (CGRectContainsPoint(subview.frame, location)) { return NO; } } return YES; } #pragma mark - Show && Dismiss - (void)show { UIViewController *appRootViewController; UIWindow *window; window = [UIApplication sharedApplication].keyWindow; appRootViewController = window.rootViewController; UIViewController *topViewController = appRootViewController; while (topViewController.presentedViewController != nil) { topViewController = topViewController.presentedViewController; } if ([topViewController.view viewWithTag:XRPopMenuViewTag]) { [[topViewController.view viewWithTag:XRPopMenuViewTag] removeFromSuperview]; } self.frame = topViewController.view.bounds; [topViewController.view addSubview:self]; [self backViewGradualChangeByValue:1.0f animateTime:XRPopMenuViewAnimationTime]; [self riseAnimation]; } - (void)dismiss:(id)sender { [self dropAnimation]; double delayInSeconds = XRPopMenuViewAnimationTime + XRPopMenuViewAnimationInterval * (self.buttons.count + 1); [self backViewGradualChangeByValue:.0f animateTime:delayInSeconds]; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ [self removeFromSuperview]; }); } - (void)backViewGradualChangeByValue:(CGFloat)value animateTime:(CGFloat)animateTime { [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:animateTime]; self.backgroundView.alpha = value; [UIView commitAnimations]; } - (void)buttonTapped:(XRPopMenuItemButton*)btn { //[self dismiss:nil]; //btn.selectedBlock(); CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; animation.delegate = self; // animation.duration = 0.2; // animation.repeatCount = 1; // animation.autoreverses = YES; // // animation.fromValue = [NSNumber numberWithFloat:1.0]; // animation.toValue = [NSNumber numberWithFloat:1.2]; // // [btn.layer addAnimation:animation forKey:@"scale-layer"]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; self.alpha = .0f; [UIView commitAnimations]; WEAKSELF dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ btn.selectedBlock(); [weakSelf removeFromSuperview]; }); // double delayInSeconds = XRPopMenuViewAnimationTime + XRPopMenuViewAnimationInterval * (self.buttons.count + 1); // dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); // dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // btn.selectedBlock(); // }); } - (void)riseAnimation { NSUInteger rowCount = self.buttons.count / COLUMN_COUNT + (self.buttons.count%COLUMN_COUNT>0?1:0); for (NSUInteger index = 0; index < self.buttons.count; index++) { XRPopMenuItemButton *button = self.buttons[index]; button.layer.opacity = 0; CGRect frame = [self frameForButtonAtIndex:index]; NSUInteger rowIndex = index / COLUMN_COUNT; NSUInteger columnIndex = index % COLUMN_COUNT; CGPoint fromPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y + (rowCount - rowIndex + 2)*200 + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); CGPoint toPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); double delayInSeconds = rowIndex * COLUMN_COUNT * XRPopMenuViewAnimationInterval; if (!columnIndex) { delayInSeconds += XRPopMenuViewAnimationInterval; } else if(columnIndex == 2) { delayInSeconds += XRPopMenuViewAnimationInterval * 2; } CABasicAnimation *positionAnimation; positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; positionAnimation.fromValue = [NSValue valueWithCGPoint:fromPosition]; positionAnimation.toValue = [NSValue valueWithCGPoint:toPosition]; positionAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.45f :1.2f :0.75f :1.0f]; positionAnimation.duration = XRPopMenuViewAnimationTime; positionAnimation.beginTime = [button.layer convertTime:CACurrentMediaTime() fromLayer:nil] + delayInSeconds; [positionAnimation setValue:[NSNumber numberWithUnsignedInteger:index] forKey:XRPopMenuViewRriseAnimationID]; positionAnimation.delegate = self; [button.layer addAnimation:positionAnimation forKey:@"riseAnimation"]; } } - (void)dropAnimation { for (NSUInteger index = 0; index < self.buttons.count; index++) { XRPopMenuItemButton *button = self.buttons[index]; CGRect frame = [self frameForButtonAtIndex:index]; NSUInteger rowIndex = index / COLUMN_COUNT; NSUInteger columnIndex = index % COLUMN_COUNT; CGPoint toPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y + (rowIndex + 2)*200 + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); CGPoint fromPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); double delayInSeconds = rowIndex * COLUMN_COUNT * XRPopMenuViewAnimationInterval; if (!columnIndex) { delayInSeconds += XRPopMenuViewAnimationInterval; } else if(columnIndex == 2) { delayInSeconds += XRPopMenuViewAnimationInterval * 2; } CABasicAnimation *positionAnimation; positionAnimation = [CABasicAnimation animationWithKeyPath:@"position"]; positionAnimation.fromValue = [NSValue valueWithCGPoint:fromPosition]; positionAnimation.toValue = [NSValue valueWithCGPoint:toPosition]; positionAnimation.timingFunction = [CAMediaTimingFunction functionWithControlPoints:0.3 :0.5f :1.0f :1.0f]; positionAnimation.duration = XRPopMenuViewAnimationTime; positionAnimation.beginTime = [button.layer convertTime:CACurrentMediaTime() fromLayer:nil] + delayInSeconds; [positionAnimation setValue:[NSNumber numberWithUnsignedInteger:index] forKey:XRPopMenuViewDismissAnimationID]; positionAnimation.delegate = self; [button.layer addAnimation:positionAnimation forKey:@"dropAnimation"]; [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:XRPopMenuViewAnimationTime]; button.alpha = 0.5f; [UIView commitAnimations]; } } #pragma mark - #pragma mark - XRPopMenuView - (void)animationDidStart:(CAAnimation *)anim { if([anim valueForKey:XRPopMenuViewRriseAnimationID]) { NSUInteger index = [[anim valueForKey:XRPopMenuViewRriseAnimationID] unsignedIntegerValue]; UIView *view = self.buttons[index]; CGRect frame = [self frameForButtonAtIndex:index]; CGPoint toPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); CGFloat toAlpha = 1.0; view.layer.position = toPosition; view.layer.opacity = toAlpha; }else if([anim valueForKey:XRPopMenuViewDismissAnimationID]) { NSUInteger index = [[anim valueForKey:XRPopMenuViewDismissAnimationID] unsignedIntegerValue]; NSUInteger rowIndex = index / COLUMN_COUNT; UIView *view = self.buttons[index]; CGRect frame = [self frameForButtonAtIndex:index]; CGPoint toPosition = CGPointMake(frame.origin.x + XRPopMenuViewImageHeight / 2.0,frame.origin.y - (rowIndex + 2)*250 + (XRPopMenuViewImageHeight + XRPopMenuViewTitleHeight) / 2.0); view.layer.position = toPosition; } } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/07 - 抖动菜单/XRPopMenuView.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,094
```objective-c // // YFShakeMenuViewController.h // BigShow1949 // // Created by zhht01 on 16/1/21. // #import <UIKit/UIKit.h> @interface YFShakeMenuViewController : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/07 - 抖动菜单/YFShakeMenuViewController.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
54
```objective-c // // YFAnimationVC03.m // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import "YFAnimationVC03.h" #import "UPStackMenu.h" @interface YFAnimationVC03 () @property (nonatomic, strong) UIView *contentView; @property (nonatomic, strong) UISegmentedControl *segmentedControl; @property (nonatomic, strong) NSMutableArray *items; @property (nonatomic, strong) UPStackMenu *stack; @end @implementation YFAnimationVC03 - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor lightGrayColor]; self.segmentedControl.selectedSegmentIndex = 0; [self segmentedClick]; } - (void)segmentedClick { // if(self.stack) // [self.stack removeFromSuperview]; // NSUInteger index = sender ? [(UISegmentedControl*)sender selectedSegmentIndex] : 0; NSUInteger index = 0; switch (index) { case 0: [self.stack setAnimationType:UPStackMenuAnimationType_progressive]; [self.stack setStackPosition:UPStackMenuStackPosition_up]; [self.stack setOpenAnimationDuration:.4]; [self.stack setCloseAnimationDuration:.4]; [self.items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { [item setLabelPosition:UPStackMenuItemLabelPosition_right]; [item setLabelPosition:UPStackMenuItemLabelPosition_left]; }]; break; default: break; } [self setStackIconClosed:YES]; } - (void)setStackIconClosed:(BOOL)closed { UIImageView *icon = [[self.contentView subviews] objectAtIndex:0]; float angle = closed ? 0 : (M_PI * (135) / 180.0); [UIView animateWithDuration:0.3 animations:^{ [icon.layer setAffineTransform:CGAffineTransformRotate(CGAffineTransformIdentity, angle)]; }]; } - (NSMutableArray *)items { if (!_items) { UPStackMenuItem *squareItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"square"] highlightedImage:nil title:@"Square"]; UPStackMenuItem *circleItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"circle"] highlightedImage:nil title:@"Circle"]; UPStackMenuItem *triangleItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"triangle"] highlightedImage:nil title:@"Triangle"]; UPStackMenuItem *crossItem = [[UPStackMenuItem alloc] initWithImage:[UIImage imageNamed:@"cross"] highlightedImage:nil title:@"Cross"]; _items = [[NSMutableArray alloc] initWithObjects:squareItem, circleItem, triangleItem, crossItem, nil]; [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { [item setTitleColor:[UIColor yellowColor]]; }]; } return _items; } - (UIView *)contentView { if (!_contentView) { _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 40)]; [_contentView setBackgroundColor:[UIColor colorWithRed:112./255. green:47./255. blue:168./255. alpha:1.]]; [_contentView .layer setCornerRadius:6]; UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cross"]]; [icon setContentMode:UIViewContentModeScaleAspectFit]; [icon setFrame:CGRectInset(_contentView .frame, 10, 10)]; [_contentView addSubview:icon]; } return _contentView; } - (UPStackMenu *)stack { if (!_stack) { _stack = [[UPStackMenu alloc] initWithContentView:self.contentView]; [_stack setCenter:CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2 + 20)]; // [stack setDelegate:self]; [_stack addItems:self.items]; [self.view addSubview:self.stack]; } return _stack; } - (UISegmentedControl *)segmentedControl { if (!_segmentedControl) { _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"one", @"two", @"three"]]; _segmentedControl.frame = CGRectMake(0, 0, 250, 35); _segmentedControl.center = CGPointMake(YFScreen.width / 2, 100); [_segmentedControl addTarget:self action:@selector(segmentedClick) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:_segmentedControl]; } return _segmentedControl; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/YFAnimationVC03.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
986
```objective-c // // UPStackMenu.m // UPStackButtonDemo // // Created by Paul Ulric on 21/01/2015. // #import "UPStackMenu.h" const static CGFloat kStackMenuDefaultItemsSpacing = 6; const static UPStackMenuStackPosition_e kStackMenuDefaultStackPosition = UPStackMenuStackPosition_up; const static UPStackMenuAnimationType_e kStackMenuDefaultAnimationType = UPStackMenuAnimationType_linear; const static BOOL kStackMenuDefaultBouncingAnimation = YES; const static NSTimeInterval kStackMenuDefaultOpenAnimationDuration = 0.4; const static NSTimeInterval kStackMenuDefaultCloseAnimationDuration = 0.4; const static NSTimeInterval kStackMenuDefaultOpenAnimationDurationOffset = 0.0; const static NSTimeInterval kStackMenuDefaultCloseAnimationDurationOffset = 0.0; @interface UPStackMenu() { UIButton *_baseButton; NSMutableArray *_items; CGSize _openedSize; CGPoint _baseButtonOpenedCenter; BOOL _isAnimating; NSUInteger _animatedItemTag; } @end @implementation UPStackMenu - (id)initWithContentView:(UIView*)contentView { self = [super initWithFrame:contentView.frame]; if(self) { [self setClipsToBounds:YES]; CGRect contentFrame = contentView.frame; contentFrame.origin = CGPointZero; [contentView setFrame:contentFrame]; _baseButton = [UIButton buttonWithType:UIButtonTypeCustom]; [_baseButton setFrame:contentFrame]; [_baseButton addTarget:self action:@selector(toggleStack:) forControlEvents:UIControlEventTouchUpInside]; [_baseButton addSubview:contentView]; [contentView setUserInteractionEnabled:NO]; [self addSubview:_baseButton]; [_baseButton addObserver:self forKeyPath:@"center" options:NSKeyValueObservingOptionNew context:nil]; _items = [NSMutableArray new]; _openedSize = _baseButton.frame.size; _itemsSpacing = kStackMenuDefaultItemsSpacing; _stackPosition = kStackMenuDefaultStackPosition; _animationType = kStackMenuDefaultAnimationType; _bouncingAnimation = kStackMenuDefaultBouncingAnimation; _openAnimationDuration = kStackMenuDefaultOpenAnimationDuration; _closeAnimationDuration = kStackMenuDefaultCloseAnimationDuration; _openAnimationDurationOffset = kStackMenuDefaultOpenAnimationDurationOffset; _closeAnimationDurationOffset = kStackMenuDefaultCloseAnimationDurationOffset; } return self; } - (void) dealloc { [_baseButton removeObserver:self forKeyPath:@"center"]; } #pragma mark - Items management - (void)addItem:(UPStackMenuItem*)item computeSize:(BOOL)compute { if(_isOpen || _isAnimating) return; [item setDelegate:self]; [item reduceAnimated:NO withDuration:0]; [_items addObject:item]; // [item setAlpha:0.]; CGPoint convertedCenter = [item centerForItemCenter:_baseButton.center]; [item setCenter:convertedCenter]; [self insertSubview:item atIndex:0]; if(compute) [self computeOpenedSize]; } - (void)addItem:(UPStackMenuItem*)item { [self addItem:item computeSize:YES]; } - (void)addItems:(NSArray*)items { [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [self addItem:obj computeSize:NO]; }]; [self computeOpenedSize]; } - (void)removeItem:(UPStackMenuItem*)item computeSize:(BOOL)compute { if(![_items containsObject:item]) return; [item removeFromSuperview]; [_items removeObject:item]; if(compute) [self computeOpenedSize]; } - (void)removeItem:(UPStackMenuItem*)item { [self removeItem:item computeSize:YES]; } - (void)removeItemAtIndex:(NSUInteger)index { if(index >= [_items count]) return; UPStackMenuItem *item = [_items objectAtIndex:index]; [self removeItem:item computeSize:YES]; } - (void)removeAllItems { [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { [self removeItem:item computeSize:NO]; }]; [self computeOpenedSize]; } - (NSArray*)items { return [NSArray arrayWithArray:_items]; } #pragma mark - Helpers - (void)computeOpenedSize { CGPoint center = CGPointMake(_baseButton.frame.size.width/2, _baseButton.frame.size.height/2); __block CGFloat height = _baseButton.frame.size.height; __block CGFloat leftOffset = 0; __block CGFloat rightOffset = 0; [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { height += item.frame.size.height + _itemsSpacing; if([item labelPosition] == UPStackMenuItemLabelPosition_left) { CGFloat itemLeftOffset = fabsf(center.x - item.itemCenter.x); if(itemLeftOffset > leftOffset) leftOffset = itemLeftOffset; } else if([item labelPosition] == UPStackMenuItemLabelPosition_right) { CGFloat itemRightOffset = fabsf(item.frame.size.width - item.itemCenter.x - center.x); if(itemRightOffset > rightOffset) rightOffset = itemRightOffset; } }]; if([_items count] > 0) height += _itemsSpacing; CGFloat width = leftOffset + _baseButton.frame.size.width + rightOffset; _openedSize = CGSizeMake(width, height); CGFloat baseButtonCenterY = _baseButton.frame.size.height/2; if(_stackPosition == UPStackMenuStackPosition_up) baseButtonCenterY = _openedSize.height - _baseButton.frame.size.height/2; _baseButtonOpenedCenter = CGPointMake(leftOffset + _baseButton.frame.size.width/2, baseButtonCenterY); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([object isEqual:_baseButton]) { if([keyPath isEqualToString:@"center"]) { [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { CGPoint convertedCenter = [item centerForItemCenter:_baseButton.center]; [item setCenter:convertedCenter]; }]; } } } #pragma mark - Customization - (void)setStackPosition:(UPStackMenuStackPosition_e)stackPosition { if(_isOpen) { NSLog(@"[UPStackMenu] Warning: trying to modify the stackPosition while the stack is open. No effect."); return; } _stackPosition = stackPosition; [self computeOpenedSize]; } - (void)setItemsSpacing:(CGFloat)itemsSpacing { _itemsSpacing = itemsSpacing; [self computeOpenedSize]; } #pragma mark - Interactions - (void)toggleStack:(id)sender { if(!_isOpen) [self openStack]; else [self closeStack]; } - (void)openStack { if(_isAnimating || _isOpen) return; _isAnimating = YES; _animatedItemTag = 0; if(_delegate && [_delegate respondsToSelector:@selector(stackMenuWillOpen:)]) [_delegate stackMenuWillOpen:self]; CGRect frame = self.frame; frame.size = _openedSize; frame.origin.x -= _baseButtonOpenedCenter.x - _baseButton.frame.size.width/2; CGFloat yOffset = _baseButtonOpenedCenter.y - _baseButton.frame.size.height/2; frame.origin.y -= (_stackPosition == UPStackMenuStackPosition_up) ? yOffset : yOffset*(-1); [self setFrame:frame]; [_baseButton setCenter:_baseButtonOpenedCenter]; NSUInteger itemsCount = [_items count]; NSInteger way = (_stackPosition == UPStackMenuStackPosition_up) ? -1 : 1; __block CGFloat y = _baseButton.frame.origin.y - _itemsSpacing; if(_stackPosition == UPStackMenuStackPosition_down) y = _baseButton.frame.origin.y + _baseButton.frame.size.height + _itemsSpacing; [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { NSTimeInterval duration = _openAnimationDuration; if(_animationType == UPStackMenuAnimationType_progressive) duration = ((idx + 1) * _openAnimationDuration) / itemsCount; else if(_animationType == UPStackMenuAnimationType_progressiveInverse) duration = ((itemsCount - idx) * _openAnimationDuration) / itemsCount; CGPoint center = CGPointMake(_baseButton.center.x, y + (item.frame.size.height/2 * way)); CGPoint translatedCenter = [item centerForItemCenter:center]; int64_t delay = idx * (_openAnimationDurationOffset*1000); dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (delay * NSEC_PER_MSEC)); dispatch_after(time, dispatch_get_main_queue(), ^{ [self moveItem:item toCenter:translatedCenter withDuration:duration opening:YES bouncing:_bouncingAnimation]; }); y += (item.frame.size.height + _itemsSpacing) * way; }]; _isOpen = YES; } - (void)closeStack { if(_isAnimating || !_isOpen) return; _isAnimating = YES; _animatedItemTag = 0; if(_delegate && [_delegate respondsToSelector:@selector(stackMenuWillClose:)]) [_delegate stackMenuWillClose:self]; NSUInteger itemsCount = [_items count]; [_items enumerateObjectsUsingBlock:^(UPStackMenuItem *item, NSUInteger idx, BOOL *stop) { NSTimeInterval duration = _closeAnimationDuration; if(_animationType == UPStackMenuAnimationType_progressive) duration = ((idx + 1) * _closeAnimationDuration) / itemsCount; else if(_animationType == UPStackMenuAnimationType_progressiveInverse) duration = ((itemsCount - idx) * _closeAnimationDuration) / itemsCount; CGPoint translatedCenter = [item centerForItemCenter:_baseButton.center]; int64_t delay = idx * (_closeAnimationDurationOffset*1000); dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (delay * NSEC_PER_MSEC)); dispatch_after(time, dispatch_get_main_queue(), ^{ [self moveItem:item toCenter:translatedCenter withDuration:duration opening:NO bouncing:_bouncingAnimation]; }); }]; _isOpen = NO; } - (void)moveItem:(UPStackMenuItem*)item toCenter:(CGPoint)center withDuration:(NSTimeInterval)duration opening:(BOOL)opening bouncing:(BOOL)bouncing { CGPoint farCenter; CGPoint nearCenter; NSInteger way = (_stackPosition == UPStackMenuStackPosition_up) ? -1 : 1; if(bouncing) { CGFloat bouncingOffset = _itemsSpacing * way; if(opening) { farCenter = CGPointMake(center.x, center.y + bouncingOffset); nearCenter = CGPointMake(center.x, center.y + (bouncingOffset/2)*-1); } else farCenter = CGPointMake(item.center.x, item.center.y + bouncingOffset); } CAKeyframeAnimation *positionAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"]; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, item.center.x, item.center.y); if(bouncing) { CGPathAddLineToPoint(path, NULL, farCenter.x, farCenter.y); if(opening) CGPathAddLineToPoint(path, NULL, nearCenter.x, nearCenter.y); } CGPathAddLineToPoint(path, NULL, center.x, center.y); positionAnimation.path = path; CGPathRelease(path); CAAnimationGroup *animationgroup = [CAAnimationGroup animation]; animationgroup.animations = @[positionAnimation]; animationgroup.duration = duration; animationgroup.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn]; animationgroup.delegate = self; [item.layer addAnimation:animationgroup forKey:@"move"]; item.center = center; if(opening) [item expandAnimated:YES withDuration:duration]; else [item reduceAnimated:YES withDuration:duration]; } - (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag { _animatedItemTag++; if(_animatedItemTag < [_items count]) return; if(_isOpen) { if(_delegate && [_delegate respondsToSelector:@selector(stackMenuDidOpen:)]) [_delegate stackMenuDidOpen:self]; } else { CGRect frame = self.frame; frame.size = _baseButton.frame.size; frame.origin.x += _baseButton.frame.origin.x; if(_stackPosition == UPStackMenuStackPosition_up) frame.origin.y += _baseButton.frame.origin.y; [self setFrame:frame]; [_baseButton setCenter:CGPointMake(frame.size.width/2, frame.size.height/2)]; if(_delegate && [_delegate respondsToSelector:@selector(stackMenuDidClose:)]) [_delegate stackMenuDidClose:self]; } _isAnimating = NO; } #pragma mark - UPStackMenuItemDelegate - (void)didTouchStackMenuItem:(UPStackMenuItem *)item { if(_delegate && [_delegate respondsToSelector:@selector(stackMenu:didTouchItem:atIndex:)]) { NSUInteger index = [_items indexOfObject:item]; if(index != NSNotFound) [_delegate stackMenu:self didTouchItem:item atIndex:index]; } } @end // // path_to_url (cn) path_to_url (en) // : Code4App.com ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/UPStackMenu.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
3,004
```objective-c // // UPStackMenuItem.h // UPStackButtonDemo // // Created by Paul Ulric on 21/01/2015. // #import <UIKit/UIKit.h> typedef enum { UPStackMenuItemLabelPosition_left = 0, UPStackMenuItemLabelPosition_right } UPStackMenuItemLabelPosition_e; @protocol UPStackMenuItemDelegate; @interface UPStackMenuItem : UIView @property (nonatomic, strong) UIImage *image; @property (nonatomic, strong) UIImage *highlightedImage; @property (nonatomic, strong) NSString *title; @property (nonatomic, readwrite) UPStackMenuItemLabelPosition_e labelPosition; @property (nonatomic, unsafe_unretained) id<UPStackMenuItemDelegate> delegate; - (id)initWithImage:(UIImage*)image; - (id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage title:(NSString*)title; - (id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage title:(NSString*)title font:(UIFont*)font; - (void)expandAnimated:(BOOL)animated withDuration:(NSTimeInterval)duration; - (void)reduceAnimated:(BOOL)animated withDuration:(NSTimeInterval)duration; - (CGPoint)itemCenter; - (CGPoint)centerForItemCenter:(CGPoint)itemCenter; - (void)setTitleColor:(UIColor*)color; @end @protocol UPStackMenuItemDelegate <NSObject> @optional - (void)didTouchStackMenuItem:(UPStackMenuItem*)item; @end// // path_to_url (cn) path_to_url (en) // : Code4App.com ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/UPStackMenuItem.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
329
```objective-c // // YFAnimationVC03.h // BigShow1949 // // Created by WangMengqi on 15/9/1. // #import <UIKit/UIKit.h> @interface YFAnimationVC03 : UIViewController @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/YFAnimationVC03.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
53
```objective-c // // UPStackMenu.h // UPStackButtonDemo // // Created by Paul Ulric on 21/01/2015. // #import <UIKit/UIKit.h> #import "UPStackMenuItem.h" typedef enum { UPStackMenuStackPosition_up = 0, UPStackMenuStackPosition_down } UPStackMenuStackPosition_e; typedef enum { UPStackMenuAnimationType_linear = 0, UPStackMenuAnimationType_progressive, UPStackMenuAnimationType_progressiveInverse } UPStackMenuAnimationType_e; @protocol UPStackMenuDelegate; @interface UPStackMenu : UIView <UPStackMenuItemDelegate> // Vertical spacing between each stack menu item @property (nonatomic, readwrite) CGFloat itemsSpacing; // Whether the items should bounce at the end of the opening animation, or a the beginning of the closing animaton @property (nonatomic, readwrite) BOOL bouncingAnimation; // Opening animation total duration (in seconds) @property (nonatomic, readwrite) NSTimeInterval openAnimationDuration; // Closing animation total duration (in seconds) @property (nonatomic, readwrite) NSTimeInterval closeAnimationDuration; // Delay between each item animation start during opening (in seconds) @property (nonatomic, readwrite) NSTimeInterval openAnimationDurationOffset; // Delay between each item animation start during closing (in seconds) @property (nonatomic, readwrite) NSTimeInterval closeAnimationDurationOffset; @property (nonatomic, readwrite) UPStackMenuStackPosition_e stackPosition; @property (nonatomic, readwrite) UPStackMenuAnimationType_e animationType; @property (nonatomic, readonly) BOOL isOpen; @property (nonatomic, unsafe_unretained) id<UPStackMenuDelegate> delegate; - (id)initWithContentView:(UIView*)contentView; - (void)addItem:(UPStackMenuItem*)item; - (void)addItems:(NSArray*)items; - (void)removeItem:(UPStackMenuItem*)item; - (void)removeItemAtIndex:(NSUInteger)index; - (void)removeAllItems; - (NSArray*)items; - (void)openStack; - (void)closeStack; @end @protocol UPStackMenuDelegate <NSObject> @optional - (void)stackMenuWillOpen:(UPStackMenu*)menu; - (void)stackMenuDidOpen:(UPStackMenu*)menu; - (void)stackMenuWillClose:(UPStackMenu*)menu; - (void)stackMenuDidClose:(UPStackMenu*)menu; - (void)stackMenu:(UPStackMenu*)menu didTouchItem:(UPStackMenuItem*)item atIndex:(NSUInteger)index; @end // // path_to_url (cn) path_to_url (en) // : Code4App.com ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/UPStackMenu.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
576
```objective-c // // UPStackMenuItem.m // UPStackButtonDemo // // Created by Paul Ulric on 21/01/2015. // #import "UPStackMenuItem.h" const static CGFloat kStackItemInternMargin = 6; const static UPStackMenuItemLabelPosition_e kStackMenuItemDefaultLabelPosition = UPStackMenuItemLabelPosition_left; @interface UPStackMenuItem() { UIButton *_imageButton; UILabel *_label; UIView *_labelContainer; UIButton *_button; BOOL _isExpanded; BOOL _isAnimating; } @end @implementation UPStackMenuItem - (id)initWithImage:(UIImage*)image { return [self initWithImage:image highlightedImage:nil title:nil]; } - (id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage title:(NSString*)title { return [self initWithImage:image highlightedImage:highlightedImage title:title font:nil]; } - (id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage title:(NSString*)title font:(UIFont*)font { self = [super initWithFrame:CGRectZero]; if(self) { _image = image; _highlightedImage = highlightedImage; _title = title; _imageButton = [UIButton buttonWithType:UIButtonTypeCustom]; [_imageButton setImage:_image forState:UIControlStateNormal]; if(_highlightedImage) [_imageButton setImage:_highlightedImage forState:UIControlStateHighlighted]; [_imageButton setFrame:CGRectMake(0, 0, MAX(_image.size.width, _highlightedImage.size.width), MAX(_image.size.height, _highlightedImage.size.height))]; _label = [[UILabel alloc] initWithFrame:CGRectZero]; [_label setLineBreakMode:NSLineBreakByClipping]; [_label setText:_title]; if(font) [_label setFont:font]; CGSize labelSize = [_title sizeWithAttributes:@{NSFontAttributeName : _label.font}]; [_label setFrame:CGRectMake(0, 0, labelSize.width, labelSize.height)]; _labelContainer = [[UIView alloc] initWithFrame:_label.frame]; [_labelContainer setClipsToBounds:YES]; [_labelContainer addSubview:_label]; CGRect frame = CGRectMake(0, 0, _labelContainer.frame.size.width + kStackItemInternMargin + _imageButton.frame.size.width, MAX(_labelContainer.frame.size.height, _imageButton.frame.size.height)); [self setFrame:frame]; _button = [UIButton buttonWithType:UIButtonTypeCustom]; [_button setFrame:self.frame]; [_button setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight]; [_button addTarget:self action:@selector(didTouch:) forControlEvents:UIControlEventTouchUpInside]; [_button addObserver:self forKeyPath:@"highlighted" options:NSKeyValueObservingOptionNew context:nil]; [self addSubview:_labelContainer]; [self addSubview:_imageButton]; [self addSubview:_button]; [self setLabelPosition:kStackMenuItemDefaultLabelPosition]; _isExpanded = YES; } return self; } - (void)dealloc { [_button removeObserver:self forKeyPath:@"highlighted"]; } #pragma mark - Helpers - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if([object isEqual:_button]) { if([keyPath isEqualToString:@"highlighted"]) { [_imageButton setHighlighted:[_button isHighlighted]]; } } } #pragma mark - Customization - (void)setLabelPosition:(UPStackMenuItemLabelPosition_e)labelPosition { _labelPosition = labelPosition; switch (_labelPosition) { case UPStackMenuItemLabelPosition_left: [_labelContainer setCenter:CGPointMake(_labelContainer.frame.size.width/2, self.frame.size.height/2)]; [_imageButton setCenter:CGPointMake(self.frame.size.width - _imageButton.frame.size.width/2, self.frame.size.height/2)]; [_label setAutoresizingMask:UIViewAutoresizingFlexibleRightMargin]; break; case UPStackMenuItemLabelPosition_right: [_labelContainer setCenter:CGPointMake(self.frame.size.width - _labelContainer.frame.size.width/2, self.frame.size.height/2)]; [_imageButton setCenter:CGPointMake(_imageButton.frame.size.width/2, self.frame.size.height/2)]; [_label setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin]; break; } } - (void)setTitleColor:(UIColor*)color { [_label setTextColor:color]; } #pragma mark - Accessors - (CGPoint)itemCenter { return _imageButton.center; } - (CGPoint)centerForItemCenter:(CGPoint)itemCenter { return CGPointMake(itemCenter.x - (_imageButton.center.x - self.frame.size.width/2), itemCenter.y); } #pragma mark - Interactions - (void)expandAnimated:(BOOL)animated withDuration:(NSTimeInterval)duration { if(_isExpanded || _isAnimating) return; _isExpanded = YES; CGRect labelFrame = _labelContainer.frame; CGFloat x = 0; if(_labelPosition == UPStackMenuItemLabelPosition_right) x = self.frame.size.width - _label.frame.size.width; labelFrame.origin.x = x; labelFrame.size.width = _label.frame.size.width; if(animated) { _isAnimating = YES; [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_labelContainer setFrame:labelFrame]; [_label setAlpha:1.]; } completion:^(BOOL finished) { _isAnimating = NO; }]; } else { [_labelContainer setFrame:labelFrame]; [_label setAlpha:1.]; } } - (void)reduceAnimated:(BOOL)animated withDuration:(NSTimeInterval)duration { if(!_isExpanded || _isAnimating) return; _isExpanded = NO; CGRect labelFrame = _labelContainer.frame; CGFloat x = 0; if(_labelPosition == UPStackMenuItemLabelPosition_left) x = self.frame.size.width; labelFrame.origin.x = x; labelFrame.size.width = 0; if(animated) { _isAnimating = YES; [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{ [_labelContainer setFrame:labelFrame]; [_label setAlpha:0.]; } completion:^(BOOL finished) { _isAnimating = NO; }]; } else { [_labelContainer setFrame:labelFrame]; [_label setAlpha:0.]; } } #pragma mark - Actions - (void)didTouch:(id)sender { if(_delegate && [_delegate respondsToSelector:@selector(didTouchStackMenuItem:)]) [_delegate didTouchStackMenuItem:self]; } @end // // path_to_url (cn) path_to_url (en) // : Code4App.com ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/03 - StackMenu/UPStackMenuItem.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
1,447
```objective-c // // YFAnimationVC06.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> #import "YFDragRadialMenu.h" @interface YFAnimationVC06 : UIViewController<YFDragRadialMenuDataSource,YFDragRadialMenuDelegate> @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/06 - DragRadialMenu/YFAnimationVC06.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
78
```objective-c // // YFAnimationVC06.m // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import "YFAnimationVC06.h" #import "YFDragRadialMenu.h" @interface YFAnimationVC06 () @end @implementation YFAnimationVC06 - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor lightGrayColor]; UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 140, 21)]; tipLabel.text = @""; tipLabel.textColor = [UIColor grayColor]; tipLabel.backgroundColor = [UIColor lightGrayColor]; [self.view addSubview:tipLabel]; } -(void)viewDidAppear:(BOOL)animated{ [super viewDidAppear:animated]; UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(presentMenu:)]; longPressRecognizer.minimumPressDuration = 1; [self.view addGestureRecognizer:longPressRecognizer]; } -(void) presentMenu:(UILongPressGestureRecognizer *)gestureRecognizer{ CGPoint location = [gestureRecognizer locationInView:self.view]; if(gestureRecognizer.state == UIGestureRecognizerStateBegan){ YFDragRadialMenu *thisMenu = [[YFDragRadialMenu alloc] initFromPoint:location withDataSource:self andDelegate:self]; [thisMenu showMenu]; } } #pragma mark - YFDragRadialMenuDelegate & YFDragRadialMenuDataSource -(NSInteger) numberOfButtonsForRadialMenu:(YFDragRadialMenu *)radialMenu{ return 6; } -(CGFloat) radiusLenghtForRadialMenu:(YFDragRadialMenu *)radialMenu{ return 100; } -(UIButton *)radialMenu:(YFDragRadialMenu *)radialMenu elementAtIndex:(NSInteger)index{ UIButton *element = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 45, 45)]; element.backgroundColor = [UIColor whiteColor]; element.layer.cornerRadius = element.bounds.size.height/2.0; element.layer.borderColor = [UIColor blackColor].CGColor; element.layer.borderWidth = 1; element.tag = index; return element; } -(void)radialMenu:(YFDragRadialMenu *)radialMenu didSelectButton:(UIButton *)button{ NSLog(@"button(element) index:%ld",(long)button.tag); [radialMenu closeMenu]; } -(UIView *)viewForCenterOfRadialMenu:(YFDragRadialMenu *)radialMenu{ UIView *centerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 90, 90)]; centerView.backgroundColor = [UIColor blackColor]; return centerView; } -(void)radialMenu:(YFDragRadialMenu *)radialMenu customizationForRadialMenuView:(UIView *)radialMenuView{ CALayer *bgLayer = [CALayer layer]; bgLayer.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5].CGColor; bgLayer.borderColor = [UIColor colorWithWhite:200.0/255.0 alpha:1].CGColor; bgLayer.borderWidth = 1; bgLayer.cornerRadius = radialMenu.menuRadius; bgLayer.frame = CGRectMake(radialMenuView.frame.size.width/2.0-radialMenu.menuRadius, radialMenuView.frame.size.height/2.0-radialMenu.menuRadius, radialMenu.menuRadius*2, radialMenu.menuRadius*2); [radialMenuView.layer insertSublayer:bgLayer atIndex:0]; } -(BOOL)canDragRadialMenu:(YFDragRadialMenu *)radialMenu{ return YES; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/06 - DragRadialMenu/YFAnimationVC06.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
786
```objective-c // // YFDragRadialMenu.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> @protocol YFDragRadialMenuDelegate; @protocol YFDragRadialMenuDataSource; @interface YFDragRadialMenu : UIView<UIGestureRecognizerDelegate> // readonly @property (nonatomic, readonly) CGPoint centerPoint; @property (nonatomic, assign) CGFloat menuRadius; // view @property (nonatomic, assign) NSInteger numberOfButtons; @property (nonatomic, strong) UIView *radialMenuView; // view() @property (nonatomic, copy) UIColor *dimBackgroundColor; // YFDragRadialMenu, , 0.3 @property (nonatomic, weak) id<YFDragRadialMenuDelegate> delegate; @property (nonatomic, weak) id<YFDragRadialMenuDataSource> dataSource; @property (nonatomic, strong) UIView *centerRadialView; // view() @property (nonatomic, strong) id radialMenuIdentifier; -(id) initFromPoint:(CGPoint)centerPoint withDataSource:(id<YFDragRadialMenuDataSource>)dataSource andDelegate:(id<YFDragRadialMenuDelegate>)delegate; -(void) showMenu; -(void) showMenuWithCompletion:(void(^)()) completion; -(void) closeMenu; -(void) closeMenuWithCompletion:(void(^)()) completion; @end @class YFDragRadialMenu; @protocol YFDragRadialMenuDataSource <NSObject> -(NSInteger)numberOfButtonsForRadialMenu:(YFDragRadialMenu *)radialMenu; -(UIButton *)radialMenu:(YFDragRadialMenu *)radialMenu elementAtIndex:(NSInteger)index; @optional -(BOOL) canDragRadialMenu:(YFDragRadialMenu *) radialMenu; -(CGFloat)radiusLenghtForRadialMenu:(YFDragRadialMenu *)radialMenu; -(UIView *)viewForCenterOfRadialMenu:(YFDragRadialMenu *)radialMenu; -(void) radialMenu:(YFDragRadialMenu *)radialMenu customizationForRadialMenuView:(UIView *) radialMenuView; @end @protocol YFDragRadialMenuDelegate <NSObject> -(void)radialMenu:(YFDragRadialMenu *)radialMenu didSelectButton:(UIButton *)button; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/06 - DragRadialMenu/YFDragRadialMenu.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
496
```objective-c // // YFRadialMenu.m // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import "YFRadialMenu.h" @interface YFRadialMenu() @property (nonatomic, strong) NSMutableDictionary *poputIDs; @property (nonatomic, strong) UIView *positionView; @property (nonatomic, strong) UILabel *distanceLabel; @property (nonatomic, strong) UILabel *distanceBetweenLabel; @property (nonatomic, strong) UILabel *angleLabel; @property (nonatomic, strong) UILabel *staggerLabel; @property (nonatomic, strong) UILabel *animationLabel; @end @implementation YFRadialMenu #pragma mark Initalizer -(id)initWithCoder:(NSCoder *)aDecoder{ self = [self initWithFrame:CGRectZero]; return self; } -(instancetype)init { self = [self initWithFrame:CGRectZero]; return self; } - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.popoutViews = [NSMutableArray new]; self.poputIDs = [NSMutableDictionary new]; self.menuIsExpanded = false; self.centerView = [self makeDefaultCenterView]; self.centerView.frame = self.bounds; self.startAngle = -75; self.distanceBetweenPopouts = 50; self.distanceFromCenter = 61; self.stagger = 0.06; self.animationDuration = 0.4; [self addSubview:self.centerView]; } return self; } #pragma mark Setters - (void) setCenterView:(UIView *)centerView { if (!centerView) { centerView = [self makeDefaultCenterView]; } _centerView = centerView; UIGestureRecognizer *tap = [UITapGestureRecognizer new]; [tap addTarget:self action:@selector(didTapCenterView:)]; [self.centerView addGestureRecognizer:tap]; } -(void)setFrame:(CGRect)frame{ [super setFrame:frame]; self.centerView.frame = self.bounds; } #pragma mark Gesture Recognizers - (void) didTapCenterView: (UITapGestureRecognizer *) sender { if (self.menuIsExpanded) { [self retract]; } else { [self expand]; } } - (void) expand { if (![self.delegate respondsToSelector:@selector(radialMenuShouldExpand:)] || [self.delegate radialMenuShouldExpand:self]) { NSInteger i = 0; for (UIView *subView in self.popoutViews) { subView.alpha = 0; [UIView animateWithDuration:self.animationDuration delay:self.stagger*i usingSpringWithDamping:0.7 initialSpringVelocity:0.4 options:UIViewAnimationOptionAllowUserInteraction animations:^{ subView.alpha = 1; subView.transform = [self getTransformForPopupViewAtIndex:i]; } completion:^(BOOL finished) { if ([self.delegate respondsToSelector:@selector(radialMenuDidExpand:)]) { [self.delegate radialMenuDidExpand:self]; } }]; i++; } self.menuIsExpanded = true; } } - (void) retract { if (![self.delegate respondsToSelector:@selector(radialMenuShouldRetract:)] || [self.delegate radialMenuShouldRetract:self]) { NSInteger i = 0; for (UIView *subView in self.popoutViews) { [UIView animateWithDuration:self.animationDuration delay:self.stagger*i usingSpringWithDamping:0.7 initialSpringVelocity:0.4 options:UIViewAnimationOptionAllowUserInteraction animations:^{ subView.transform = CGAffineTransformIdentity; subView.alpha = 0; } completion:^(BOOL finished) { if ([self.delegate respondsToSelector:@selector(radialMenuDidRetract:)]) { [self.delegate radialMenuDidRetract:self]; } }]; i++; } self.menuIsExpanded = false; } } - (void) didTapPopoutView: (UITapGestureRecognizer *) sender { UIView *view = sender.view; NSString * key = [self.poputIDs allKeysForObject:view][0]; [self.delegate radialMenu:self didSelectPopoutWithIndentifier:key]; } #pragma mark Popout Views - (void) addPopoutView: (UIView *) popoutView withIndentifier: (NSString *) identifier { if (!popoutView){ popoutView = [self makeDefaultPopupView]; } [self.popoutViews addObject:popoutView]; [self.poputIDs setObject:popoutView forKey:identifier]; UIGestureRecognizer *tap = [UITapGestureRecognizer new]; [tap addTarget:self action:@selector(didTapPopoutView:)]; [popoutView addGestureRecognizer:tap]; popoutView.alpha = 0; [self addSubview:popoutView]; [self sendSubviewToBack:popoutView]; popoutView.center = CGPointMake(self.bounds.origin.x + self.bounds.size.width/2,self.bounds.origin.y + self.bounds.size.height/2); } -(UIView *)getPopoutViewWithIndentifier:(NSString *)identifier { return [self.poputIDs objectForKey:identifier]; } #pragma mark Make Default Views - (UIView *) makeDefaultCenterView { UIView *view = [UIView new]; view.layer.cornerRadius = self.frame.size.width/2; view.backgroundColor = [UIColor redColor]; view.layer.shadowColor = [[UIColor blackColor] CGColor]; view.layer.shadowOpacity = 0.6; view.layer.shadowRadius = 2.0; view.layer.shadowOffset = CGSizeMake(0, 3); return view; } - (UIView *) makeDefaultPopupView { UIView *view = [UIView new]; view.frame = CGRectMake(0, 0, self.frame.size.width/1.5, self.frame.size.height / 1.5); view.layer.cornerRadius = view.frame.size.width/2; view.backgroundColor = [UIColor blueColor]; view.layer.shadowColor = [[UIColor blackColor] CGColor]; view.layer.shadowOpacity = 0.6; view.layer.shadowRadius = 3.0; view.layer.shadowOffset = CGSizeMake(0, 3); return view; } #pragma mark Helper Methods - (CGAffineTransform) getTransformForPopupViewAtIndex: (NSInteger) index { CGFloat newAngle = self.startAngle + (self.distanceBetweenPopouts * index); CGFloat deltaY = -self.distanceFromCenter * cos(newAngle/ 180.0 * M_PI); CGFloat deltaX = self.distanceFromCenter * sin(newAngle/ 180.0 * M_PI); return CGAffineTransformMakeTranslation(deltaX, deltaY); } - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{ if (CGRectContainsPoint(self.bounds, point)) { return true; } for (UIView *subView in self.popoutViews) { if (CGRectContainsPoint(subView.frame, point)) { return true; } } return false; } - (void) enableDevelopmentMode:(UIViewController *)superViewController { UIView *positionView = [UIView new]; CGRect screenRect = [UIScreen mainScreen].bounds; positionView.frame = CGRectMake(screenRect.origin.x, screenRect.origin.y, screenRect.size.width,110); positionView.backgroundColor = [UIColor clearColor]; [superViewController.view addSubview:positionView]; [superViewController.view bringSubviewToFront:positionView]; self.distanceLabel = [UILabel new]; self.distanceLabel.frame = CGRectMake(10, 20, 300, 20); [positionView addSubview:self.distanceLabel]; self.distanceLabel.text = [NSString stringWithFormat:@": %.02f", self.distanceFromCenter]; self.distanceLabel.font = [UIFont fontWithName:@"Avenir" size:16]; self.angleLabel = [UILabel new]; self.angleLabel.frame = CGRectMake(10, CGRectGetMaxY(self.distanceLabel.frame) + 10, 300, 20); [positionView addSubview:self.angleLabel]; self.angleLabel.text = [NSString stringWithFormat:@": %.02f", self.startAngle]; self.angleLabel.font = [UIFont fontWithName:@"Avenir" size:16]; self.distanceBetweenLabel = [UILabel new]; self.distanceBetweenLabel.frame = CGRectMake(10, CGRectGetMaxY(self.angleLabel.frame) + 10, 200, 20); [positionView addSubview:self.distanceBetweenLabel]; self.distanceBetweenLabel.text = [NSString stringWithFormat:@": %.02f", self.distanceBetweenPopouts]; self.distanceBetweenLabel.font = [UIFont fontWithName:@"Avenir" size:16]; UISlider *distanceSlider = [UISlider new]; distanceSlider.frame = CGRectMake(200, self.distanceBetweenLabel.frame.origin.y, screenRect.size.width - 225, 20); [positionView addSubview:distanceSlider]; distanceSlider.maximumValue = 180; distanceSlider.minimumValue = 0; distanceSlider.value = self.distanceBetweenPopouts; [distanceSlider addTarget:self action:@selector(distanceSliderChanged:) forControlEvents:UIControlEventValueChanged]; self.staggerLabel = [UILabel new]; self.staggerLabel.frame = CGRectMake(10, CGRectGetMaxY(self.distanceBetweenLabel.frame) + 10, 200, 20); [positionView addSubview:self.staggerLabel]; self.staggerLabel.text = [NSString stringWithFormat:@" %.02f", self.stagger]; self.staggerLabel.font = [UIFont fontWithName:@"Avenir" size:16]; UISlider *staggerSlider = [UISlider new]; staggerSlider.frame = CGRectMake(200, self.staggerLabel.frame.origin.y, screenRect.size.width - 225, 20); [positionView addSubview:staggerSlider]; staggerSlider.maximumValue = 1; staggerSlider.minimumValue = 0; staggerSlider.value = self.stagger; [staggerSlider addTarget:self action:@selector(staggerSliderChanged:) forControlEvents:UIControlEventValueChanged]; // positionViewframe CGFloat postionViewY = CGRectGetMinX(self.distanceLabel.frame) - 10; CGFloat postionViewH = CGRectGetMaxY(self.staggerLabel.frame) + 10 - postionViewY; positionView.frame = CGRectMake(screenRect.origin.x, 64, screenRect.size.width,postionViewH); for (UIView *subView in self.popoutViews) { [subView removeGestureRecognizer:[subView gestureRecognizers][0]]; UIPanGestureRecognizer *panner = [UIPanGestureRecognizer new]; [panner addTarget:self action:@selector(didPanPopout:)]; [subView addGestureRecognizer:panner]; } } -(void) didPanPopout:(UIPanGestureRecognizer *)sender { UIView *view = sender.view; NSInteger i = [self.popoutViews indexOfObject:view]; CGPoint point = [sender locationInView:self]; CGFloat centerX = self.bounds.origin.x + self.bounds.size.width/2; CGFloat centerY = self.bounds.origin.y + self.bounds.size.height/2; if (sender.state == UIGestureRecognizerStateChanged) { // Do Calculations CGFloat deltaX = point.x - centerX; CGFloat deltaY = point.y - centerY; CGFloat angle = atan2(deltaX, -deltaY) * 180.0 / M_PI ; CGFloat distanceFromCenter = sqrt(pow(point.x - centerX, 2) + pow(point.y - centerY, 2)); // Assign Results self.distanceFromCenter = distanceFromCenter; self.startAngle = angle - self.distanceBetweenPopouts * i; // Change Labels self.distanceLabel.text = [NSString stringWithFormat:@"Distance From Center: %.02f", self.distanceFromCenter]; self.angleLabel.text = [NSString stringWithFormat:@"Start Angle: %.02f", self.startAngle]; // Change Position of Views view.center = point; view.transform = CGAffineTransformIdentity; NSInteger i = 0; for (UIView *subView in self.popoutViews) { if (subView != view) { subView.transform = [self getTransformForPopupViewAtIndex:i]; } i++; } } else if (sender.state == UIGestureRecognizerStateEnded) { view.center = CGPointMake(centerX, centerY); NSInteger i = 0; for (UIView *subView in self.popoutViews) { subView.transform = [self getTransformForPopupViewAtIndex:i]; i++; } } } - (void)distanceSliderChanged:(UISlider *)sender { if (!self.menuIsExpanded){ [self expand]; } self.distanceBetweenPopouts = sender.value; self.distanceBetweenLabel.text = [NSString stringWithFormat:@"Distance Between: %.02f", self.distanceBetweenPopouts]; NSInteger i = 0; for (UIView *subView in self.popoutViews) { subView.transform = [self getTransformForPopupViewAtIndex:i]; i++; } } - (void)staggerSliderChanged:(UISlider *)sender { self.stagger = sender.value; self.staggerLabel.text = [NSString stringWithFormat:@"Stagger In Seconds: %.02f", self.stagger]; } - (void)durationSliderChanged:(UISlider *)sender { self.animationDuration = sender.value; self.animationLabel.text = [NSString stringWithFormat:@"Duration In Seconds: %.02f", self.animationDuration]; } @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/04 - RadialMenu/YFRadialMenu.m
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
2,827
```objective-c // // YFAnimationVC04.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> #import "YFRadialMenu.h" @interface YFAnimationVC04 : UIViewController<YFRadialMenuDelegate> @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/04 - RadialMenu/YFAnimationVC04.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
69
```objective-c // // YFRadialMenu.h // BigShow1949 // // Created by WangMengqi on 15/9/2. // #import <UIKit/UIKit.h> @class YFRadialMenu; @protocol YFRadialMenuDelegate <NSObject> @optional -(void)radialMenu:(YFRadialMenu *)radialMenu didSelectPopoutWithIndentifier: (NSString *) identifier; -(BOOL)radialMenuShouldExpand:(YFRadialMenu *)radialMenu; -(void)radialMenuDidExpand:(YFRadialMenu *)radialMenu; -(BOOL)radialMenuShouldRetract:(YFRadialMenu *)radialMenu; -(void)radialMenuDidRetract:(YFRadialMenu *)radialMenu; @end @interface YFRadialMenu : UIView - (void) addPopoutView: (UIView *) popoutView withIndentifier: (NSString *) identifier; - (UIView *) getPopoutViewWithIndentifier: (NSString *) identifier; - (void) expand; - (void) retract; - (void) enableDevelopmentMode:(UIViewController *)superViewController; @property (nonatomic, weak) NSObject<YFRadialMenuDelegate> *delegate; @property (nonatomic, strong) UIView *centerView; @property (nonatomic, strong) NSMutableArray *popoutViews; @property CGFloat popoutViewSize; @property CGFloat distanceFromCenter; @property CGFloat distanceBetweenPopouts; @property CGFloat startAngle; @property CGFloat animationDuration; @property NSTimeInterval stagger; @property BOOL menuIsExpanded; @end ```
/content/code_sandbox/BigShow1949/Classes/07 - Animations(动画)/01 - 弹出菜单/04 - RadialMenu/YFRadialMenu.h
objective-c
2016-05-05T08:19:43
2024-08-07T09:29:21
BigShow1949
BigShow1949/BigShow1949
1,121
329