每当 StaticBackgroundView 移动时 - 背景图像中心也必须调整。
在下面给出的示例中,每次在 PanGesture 更新期间移动 StaticBackgroundView 时都会调用 updateBackgroundImage。
-(void)updateBackgroundImage
{
imageView.center = CGPointMake(( (imageView.image.size.width*0.5) - self.center.x) + (self.bounds.size.width*0.5)
, ((imageView.image.size.height*0.5) - self.center.y) + (self.bounds.size.height*0.5));
}
如果您将 StaticBackgroundView 向右移动,图像将向左移动,并且在 StaticBackgroundView 下方看起来保持静止。
下面的示例代码允许您使用手指移动 StaticBackgroundView 并在下方显示静态图像:
StaticBackgroundView.h
#import <UIKit/UIKit.h>
@interface StaticBackgroundView : UIView
-(void)updateBackgroundImage;
@end
StaticBackgroundView.m
#import "StaticBackgroundView.h"
@implementation StaticBackgroundView {
UIImageView *imageView;
}
// Must be init'd from code or won't work
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSLog(@"StaticBackgroundView:initWithFrame");
if([[UIDevice currentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
{
if ([[UIScreen mainScreen] bounds].size.height == 568)
{
NSLog(@"iPhone5 image");
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage-568h"]];
}
else
{
NSLog(@"iPhone4 image");
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"myImage"]];
}
}
self.clipsToBounds = YES;
[self updateBackgroundImage];
[self addSubview:imageView];
[self sendSubviewToBack:imageView];
}
return self;
}
-(void)updateBackgroundImage
{
imageView.center = CGPointMake(( (imageView.image.size.width*0.5) - self.center.x) + (self.bounds.size.width*0.5)
, ((imageView.image.size.height*0.5) - self.center.y) + (self.bounds.size.height*0.5));
}
ViewController.m
#import "ViewController.h"
#import "StaticBackgroundView.h"
@interface ViewController ()
@property (strong, nonatomic) StaticBackgroundView *outletStaticView;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.outletStaticView = [[StaticBackgroundView alloc] initWithFrame:CGRectMake(100, 100, 120, 150)];
[self.view addSubview:self.outletStaticView];
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[self.outletStaticView addGestureRecognizer:panGestureRecognizer];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)handlePan:(UIPanGestureRecognizer *)gestureRecognizer
{
if([gestureRecognizer state] == UIGestureRecognizerStateChanged)
{
CGPoint translation = [gestureRecognizer translationInView:self.view];
gestureRecognizer.view.center = CGPointMake(gestureRecognizer.view.center.x + translation.x, gestureRecognizer.view.center.y + translation.y);
[gestureRecognizer setTranslation:CGPointMake(0, 0) inView:self.view];
StaticBackgroundView * theView = (StaticBackgroundView*)gestureRecognizer.view;
[theView updateBackgroundImage];
}
}
@end