本文共 1642 字,大约阅读时间需要 5 分钟。
在 Objective-C 中实现一个跳动的桃心,可以通过 Core Graphics 和 UIView 动画来实现。以下是一个完整的示例代码,展示如何创建一个简单的应用程序,并绘制一个跳动的桃心。
在 Xcode 中创建一个新的 iOS 项目,选择 “Single View App” 模板。
在 ViewController.m 中实现桃心的绘制和动画效果。以下是完整的代码:
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)drawHeart { // 1. 获取当前视图 CGRect heartFrame = CGRectMake(self.view.frame.size.width / 2 - 25, self.view.frame.size.height / 2 - 25, 50, 50); // 2. 初始化路径 CGContextRef heartContext = UIGraphicsGetCurrentContext(); // 3. 设置线宽和颜色 CGContextSetLineWidth(heartContext, 5); CGContextSetStrokeColor(heartContext, [UIColor redColor].CGColor); // 4. 绘制桃心 CGContextBeginPath(heartContext); CGContextMoveToPoint(heartContext, heartFrame.origin.x + 25, heartFrame.origin.y + 25); CGContextLineTo(heartContext, heartFrame.origin.x + 50, heartFrame.origin.y + 25); CGContextLineTo(heartContext, heartFrame.origin.x + 25, heartFrame.origin.y + 50); CGContextLineTo(heartContext, heartFrame.origin.x, heartFrame.origin.y + 25); CGContextClosePath(heartContext); // 5. 添加动画效果 CABasicAnimation *animation = [CABasicAnimation animation]; animation.duration = 1; animation.repeatCount = 2; animation.autoreverse = YES; // 6. 应用动画 [self.view.layer addAnimation:animation]; [self.view.layer setCornerRadius(heartFrame.size.width / 2)]; // 7. 绘制动画 UIGraphicsBeginImageContext(heartFrame.size); CGContextDrawPath(heartContext, heartFrame); UIGraphicsEndImageContext();}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { // 转载地址:http://kysfk.baihongyu.com/