如何使用iphone sdk中的手势在框架中移动图像
Posted
技术标签:
【中文标题】如何使用iphone sdk中的手势在框架中移动图像【英文标题】:How to move image with in the frame using gestures in iphone sdk 【发布时间】:2012-08-04 11:01:15 【问题描述】:我是使用手势的新手,通过使用我想在框架中移动图像的手势。 任何人都可以在这方面提供帮助.. 你可以找到下面的图片。
【问题讨论】:
你面临的问题是什么你没有提到... Leena,实际上我有一个 UIView,在这个视图中我有 UIImageView(给定参考图像中的红色正方形)......有一个选项可以从顶部选择一个图像......这里选定的图像应该只移动这个红色方块。你能建议实现这一目标的最佳方法吗?谢谢。 github.com/elc/iCodeBlogDemoPhotoBoard 看这个例子。 是的,Leena,谢谢分享,但我有这个样本...要求是我需要限制所选图像仅在正方形中移动..任何建议请... 【参考方案1】:嗨,VSN 首先从您的图像视图中剪切选定的部分
使用此代码
- (void)viewDidLoad
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tactile_noise.png"]];
self.imageCropper = [[BJImageCropper alloc] initWithImage:[UIImage imageNamed:@"gavandme.jpg"] andMaxSize:CGSizeMake(1024, 600)];
[self.view addSubview:self.imageCropper];
self.imageCropper.center = self.view.center;
self.imageCropper.imageView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.imageCropper.imageView.layer.shadowRadius = 3.0f;
self.imageCropper.imageView.layer.shadowOpacity = 0.8f;
self.imageCropper.imageView.layer.shadowOffset = CGSizeMake(1, 1);
[self.imageCropper addObserver:self forKeyPath:@"crop" options:NSKeyValueObservingOptionNew context:nil];
if (SHOW_PREVIEW)
self.preview = [[UIImageView alloc] initWithFrame:CGRectMake(10,10,self.imageCropper.crop.size.width * 0.1, self.imageCropper.crop.size.height * 0.1)];
self.preview.image = [self.imageCropper getCroppedImage];
self.preview.clipsToBounds = YES;
self.preview.layer.borderColor = [[UIColor whiteColor] CGColor];
self.preview.layer.borderWidth = 2.0;
[self.view addSubview:self.preview];
检查这个例子
https://github.com/barrettj/BJImageCropper/downloads
或要裁剪选定的图像部分,请这样做
// Create the image from a png file
UIImage *image = [UIImage imageNamed:@"prgBinary.jpg"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// Get size of current image
CGSize size = [image size];
// Frame location in view to show original image
[imageView setFrame:CGRectMake(0, 0, size.width, size.height)];
[[self view] addSubview:imageView];
[imageView release];
// Create rectangle that represents a cropped image
// from the middle of the existing image
CGRect rect = CGRectMake(size.width / 4, size.height / 4 ,
(size.width / 2), (size.height / 2));
// Create bitmap image from original image data,
// using rectangle to specify desired crop area
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
// Create and show the new image from bitmap data
imageView = [[UIImageView alloc] initWithImage:img];
[imageView setFrame:CGRectMake(0, 200, (size.width / 2), (size.height / 2))];
[[self view] addSubview:imageView];
[imageView release];
参考这个
http://mobiledevelopertips.com/graphics/how-to-crop-an-image.html
或者要调整 uiiamgeview 的大小,请这样做
- (UIImage *)resizeImage:(UIImage*)image newSize:(CGSize)newSize
CGRect newRect = CGRectIntegral(CGRectMake(0, 0, newSize.width, newSize.height));
CGImageRef imageRef = image.CGImage;
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
// Set the quality level to use when rescaling
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, newSize.height);
CGContextConcatCTM(context, flipVertical);
// Draw into the context; this scales the image
CGContextDrawImage(context, newRect, imageRef);
// Get the resized image from the context and a UIImage
CGImageRef newImageRef = CGBitmapContextCreateImage(context);
UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
CGImageRelease(newImageRef);
UIGraphicsEndImageContext();
return newImage;
裁剪或调整图像大小以应用UIPanGestureRecognizer
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
[panRecognizer setMinimumNumberOfTouches:1];
[panRecognizer setMaximumNumberOfTouches:1];
[panRecognizer setDelegate:self];
[holderView addGestureRecognizer:panRecognizer];
-(void)move:(id)sender
[[[(UITapGestureRecognizer*)sender view] layer] removeAllAnimations];
[self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan)
firstX = [[sender view] center].x;
firstY = [[sender view] center].y;
translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY+translatedPoint.y);
[[sender view] setCenter:translatedPoint];
if([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
CGFloat finalX = translatedPoint.x + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].x);
CGFloat finalY = translatedPoint.y + (.35*[(UIPanGestureRecognizer*)sender velocityInView:self.view].y);
if(UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation]))
if(finalX < 0)
finalX = 0;
else if(finalX > 768)
finalX = 768;
if(finalY < 0)
finalY = 0;
else if(finalY > 1024)
finalY = 1024;
else
if(finalX < 0)
finalX = 0;
else if(finalX > 1024)
finalX = 768;
if(finalY < 0)
finalY = 0;
else if(finalY > 768)
finalY = 1024;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:.35];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[[sender view] setCenter:CGPointMake(finalX, finalY)];
[UIView commitAnimations];
【讨论】:
【参考方案2】://NSURL CONNECTION WITH JSON PARSING:
https://www.dropbox.com/s/ubmaulkdhbdqha1/ViewController.m
ViewController.h
@interface ViewController : UIViewController<UITableViewDelegate,UITableViewDataSource>
IBOutlet UITableView *tableView1;
NSArray *practice_ArrayForDisplayingEx;
NSMutableArray *arrRespone;
NSMutableData *responseData;
NSMutableDictionary *resultsDictionary;
NSURLConnection *urlConnection;
@property(nonatomic,strong) IBOutlet UITableView *tableView1;
@property (nonatomic, strong) NSMutableData *responseData;
@end
ViewController.m
- (void)viewDidLoad
arrRespone=[NSMutableArray new];
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.indiaglitz.com/json/vod_menu_init.asp"]];
urlConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
[self.responseData appendData:data];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
[self.responseData setLength:0];
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
NSLog(@"didFailWithError");
// NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]);
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
NSLog(@"connectionDidFinishLoading");
NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
resultsDictionary = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
NSDictionary *arrDetails=[[resultsDictionary objectForKey:@"menu"] objectAtIndex:0] ;
NSDictionary *genr=[[arrDetails valueForKey:@"categories"] objectAtIndex:0];
NSLog(@"array detailsarray ====>%@",arrDetails);
NSLog( @"genreee arrray==%@",genr);
//NSLog(@"genrvalueeee -----%@",[genr valueForKey:@"genre"]);
NSLog(@"counttttt===%d",[[genr valueForKey:@"genre" ] count]);
NSLog(@"genre objectatindex==%@",[genr valueForKey:@"cliptype"]);
for (int i=0;i<[[genr valueForKey:@"genre" ] count];i++)
NSDictionary *strDetails=[[genr valueForKey:@"genre"] objectAtIndex:i];
NSString *str=[strDetails valueForKey:@"gname"];
NSLog(@"First string details===>%@",str);
[arrRespone addObject:str];
NSLog(@"response ====>%@",arrRespone);
[tableView1 reloadData];
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
NSLog(@"numberOfSectionsInTableView");
return 1;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
return 45;
NSLog(@"heightForRowAtIndexPath");
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
NSLog(@"numberOfRowsInSection");
return [arrRespone count];
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
NSLog(@"inside tableview");
static NSString *CellIdentifier = @"TableCell";
//TableCell *cell = (TableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier];
// cell.textLabel.text=[arrRespone objectAtIndex:indexPath.row];
NSLog(@"cellvalue:%@",cell.textLabel.text);
NSLog(@"inside numberofRowsInsection");
// Configure the cell...
cell.textLabel.text = [arrRespone objectAtIndex:indexPath.row];
return cell;
- (void)didReceiveMemoryWarning
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
【讨论】:
请编辑您的答案并格式化代码以使其可读以上是关于如何使用iphone sdk中的手势在框架中移动图像的主要内容,如果未能解决你的问题,请参考以下文章