objective-c - objective-c : fix distance between images in touches moved

标签 objective-c ios core-graphics

在执行移动触摸时,如何设置与新图像(点)具有相同固定距离的图像(点)?

enter image description here

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:touch.view];

        UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Crayon_Black.png"]];
        imageView.center = touchLocation;    

    [drawImage addSubview:imageView];
}

我希望这是有道理的。我只需要完成我的学校项目。提前谢谢大家。

最佳答案

只要您不移动手指太快,此解决方案就有效:

@interface ViewController : UIViewController {
    CGPoint lastLocation_;
    CGFloat accumulatedDistance_;
}

...

-(CGFloat) distanceFromPoint:(CGPoint)p1 ToPoint:(CGPoint)p2 {
    CGFloat xDist = (p2.x - p1.x);
    CGFloat yDist = (p2.y - p1.y);
    return sqrt((xDist * xDist) + (yDist * yDist));
}              

-(void) addImageAtLocation:(CGPoint)location {
    UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Crayon_Black.png"]];
    imageView.center = location;
    [self.view addSubview:imageView];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    lastLocation_ = [[touches anyObject] locationInView:self.view];
    accumulatedDistance_ = 0;
    [self addImageAtLocation:lastLocation_];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];

    CGFloat distance = [self distanceFromPoint:touchLocation ToPoint:lastLocation_];
    accumulatedDistance_ += distance;
    CGFloat fixedDistance = 40;
    if (accumulatedDistance_ > fixedDistance) {
        [self addImageAtLocation:touchLocation];
        while (accumulatedDistance_ > fixedDistance) {
            accumulatedDistance_ -= fixedDistance;
        }
    }

    lastLocation_ = touchLocation;
}

关于objective-c - objective-c : fix distance between images in touches moved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11669386/

相关文章:

ios - 如何从数组中的字符串数组中获取每个值

ios - 如何在单击按钮时使标签可编辑并显示键盘以键入文本?

ios - 使 UIButton 大于其图像

macos - Mac OS X : How to draw multiple NSViews into a new, 多页 PDF?

iphone - @autoreleasepool 做什么?

ios - 在循环中重复分配 NSString 同时避免内存泄漏

ios - SwiftUI 不同 View 之间的导航

ios - 如何在不使用任何形式的查找表的情况下在 Swift for iOS 8 中列出(几乎)所有表情符号?

ios - 尝试使用渐变进行实时绘图时出现性能问题

ios - 如何使用多个变换为 CATransform3D 制作动画?