以下文件将一系列形状加载到 UIViewController 中。每个形状随机放置在屏幕上。我可以使用下面的代码来水平改变图像的形状,但是我无法在 UIView 上移动图像的 x 和 y 坐标。如何将形状移动到屏幕上的不同位置?下面改变了 UIView 的宽度:
[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(0, 0, 100, 5)];}];
视图控制器.h
#import <UIKit/UIKit.h>
#import "Shape.h"
@interface ViewController : UIViewController
@end
视图控制器.m
#import "ViewController.h"
@implementation ViewController
UIView *box;
int screenHeight;
int screenWidth;
int x;
int y;
Shape * shape;
- (void)viewDidLoad
{
CGRect screenRect = [[UIScreen mainScreen] bounds];
screenHeight = screenRect.size.height;
screenWidth = screenRect.size.width;
box = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 5)];
[self.view addSubview:box];
for (int i = 0; i<3; i++) {
x = arc4random() % screenWidth;
y = arc4random() % screenHeight;
shape =[[Shape alloc] initWithX:x andY:y];
[box addSubview:shape];
[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(moveTheShape:) userInfo:shape repeats:YES];
}
}
-(void) moveTheShape:(NSTimer*)timer
{
//[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(100, 0, 100, 5)];}];
[UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setBounds:CGRectMake(0, 0, 100, 5)];}];
}
@end
形状.h
#import <UIKit/UIKit.h>
@interface Shape : UIView;
- (id) initWithX: (int)xVal andY: (int)yVal;
@end
形状.m
#import "Shape.h"
@implementation Shape
- (id) initWithX:(int )xVal andY:(int)yVal {
self = [super initWithFrame:CGRectMake(xVal, yVal, 5, 5)];
self.backgroundColor = [UIColor redColor];
return self;
}
@end