0

以下文件将一系列形状加载到 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
4

1 回答 1

1

在您的 moveTheShape 方法中,您需要设置框架,而不是边界,并将 CGRectMake 中的 x 和 y 值设置为 0 以外的值。

您可以像这样在 moveTheShape 方法中获取原始 x 和 y 值:

 -(void) moveTheShape:(NSTimer*)timer {
        CGRect frame = [timer.userInfo frame];
        float frameX = frame.origin.x;
        float frameY = frame.origin.y;
        NSLog(@"X component is:%f   Y component is:%f",frameX,frameY);
        [UIView animateWithDuration:0.5f animations:^{[[timer userInfo] setFrame:CGRectMake(200, 100, 5, 5)];}];
    }
于 2012-06-07T21:59:35.110 回答