Привет всем У меня есть spritekit сцены «Меню» что я выгрузку UIView как подвид (CGScratchViewController.xib)сенсорный координаты/расположение искажается
-(void)addscratchView:(SKView*)view
{
CGRect viewFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
//ScratchableView : UIView
myScratchView = [[ScratchView alloc]initWithFrame:viewFrame ];
self.name = @"menuScene";
[self.view addSubview:myScratchView];
}
класс ScratchableView загружает слой, который я могу стереть с мой палец рисунка наложения показывает рисунок ниже
Код кажется работающим, однако прикосновения отключены и кажутся «масштабированными» каким-то образом, что означает, что если я рисую в верхнем левом углу, то прикосновение находится в правильном месте , но перетаскивая палец наружу, и прикосновение становится все более искаженным. - любые мысли на что обращать внимание, чтобы исправить эту (я новичок делает новичку ошибок)
Scratchableview.h
// Created by Olivier Yiptong on 11-01-11.
//
#import "ScratchableView.h"
@implementation ScratchableView
@synthesize contentScale;
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
scratchable = [UIImage imageNamed:@"scratchable.jpg"].CGImage;
width = CGImageGetWidth(scratchable);
height = CGImageGetHeight(scratchable);
self.opaque = NO;
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceGray();
CFMutableDataRef pixels = CFDataCreateMutable(NULL , width * height);
alphaPixels = CGBitmapContextCreate(CFDataGetMutableBytePtr(pixels) , width , height , 8 , width , colorspace , kCGImageAlphaNone);
provider = CGDataProviderCreateWithCFData(pixels);
CGContextSetFillColorWithColor(alphaPixels, [UIColor blackColor].CGColor);
CGContextFillRect(alphaPixels, frame);
CGContextSetStrokeColorWithColor(alphaPixels, [UIColor whiteColor].CGColor);
CGContextSetLineWidth(alphaPixels, 20.0);
CGContextSetLineCap(alphaPixels, kCGLineCapRound);
CGImageRef mask = CGImageMaskCreate(width, height, 8, 8, width, provider, nil, NO);
scratched = CGImageCreateWithMask(scratchable, mask);
CGImageRelease(mask);
CGColorSpaceRelease(colorspace);
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextDrawImage(UIGraphicsGetCurrentContext() , [self bounds] , scratched);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
if([[touch view] isKindOfClass:[UIImageView class]]){
CGPoint point= [touch locationInView:touch.view];
NSLog(@"%f%f",point.x,point.y);
location = point;
}
firstTouch = YES;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event touchesForView:self] anyObject];
if (firstTouch) {
firstTouch = NO;
previousLocation = [touch previousLocationInView:self];
} else {
location = [touch locationInView:self];
previousLocation = [touch previousLocationInView:self];
}
// Render the stroke
[self renderLineFromPoint:previousLocation toPoint:location];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event touchesForView:self] anyObject];
if (firstTouch) {
firstTouch = NO;
previousLocation = [touch previousLocationInView:self];
[self renderLineFromPoint:previousLocation toPoint:location];
}
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
}
- (void) renderLineFromPoint:(CGPoint)start toPoint:(CGPoint)end {
CGContextMoveToPoint(alphaPixels, start.x, start.y);
CGContextAddLineToPoint(alphaPixels, end.x, end.y);
CGContextStrokePath(alphaPixels);
[self setNeedsDisplay];
}
- (void)dealloc {
CGContextRelease(alphaPixels);
CGImageRelease(scratchable);
CGDataProviderRelease(provider);
}
и Menuscene
-(void)didMoveToView:(SKView *)view {
self.userInteractionEnabled = YES;
SKView * skView = (SKView *)self.view;
skView.showsFPS = YES;
skView.showsNodeCount = YES;
// [self createButtons ];
[self addscratchView:view]; //for testing
}
-(void)addscratchView:(SKView*)view
{
CGRect viewFrame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
myScratchView = [[ScratchView alloc]initWithFrame:viewFrame ];
self.name = @"menuScene";
[self.view addSubview:myScratchView];
}
I «Я пытался конвертировать координаты ... все еще не так много удачи (может быть, это не правильная вещь делать в любом случае ..
//convert between view coordinates and scene coordinates
//coordinate system is not the same in a Sprite Kit scene as they are in a UIView
UITouch *touch = [[event allTouches] anyObject];
CGPoint touchlocation = [touch locationInView:touch.view];
spriteView = (Menu *) spriteView.scene.view;
CGPoint positionInScene = [self convertPoint:touchlocation fromCoordinateSpace:spriteView.scene.view];
Видео эффекта/искаженные штрихи https://www.youtube.com/watch?v=dMrcufcKpao
что я сделал в конце было изменение @implementation GameViewController, удаление - (void) viewdidload, замена на - (void) viewWillLayoutSubviews, scene.scaleMode = SKSceneScaleModeAspectFill; Это связано с тем, что в тот момент, когда система вызывает метод viewDidLoad, в вызывающей иерархии не добавляется представление. Поэтому размер и ориентацию вида не могут быть скорректированы (по крайней мере, это мое понимание?) это, казалось, устранило проблему.спасибо Рыцарь дракона, он поставил меня на путь к правильному решению! – StackBuddy
вид тот же подход, но заполнитель для аспект может не работать для вас на разных устройствах, я бы тестировал на 4, 5 и 6 (только один) и iPad – Knight0fDragon