2016-07-17 4 views
1

사용자 정의 UIViewCALayer에 추가하려고하는데 렌더되지 않습니다.CALayer에 UIView를 추가하는 방법

다른보기에 사용자 지정보기가 추가되지 않습니다. 대신 CALayer에 직접 추가하려고합니다.

다른보기 (예 : [self.view addSubview:customView])에 맞춤보기를 추가하면 작동하지만 어떤 이유로 화면이 터치되는 순간 충돌이 발생하기 시작합니다.

CustomView *customView = [[CustomView alloc] initWithFrame:frame]; 

//I'm not adding the custom view to another view 
//Instead I'm trying to add it to a CALayer 

CALayer *layer = [CALayer layer]; 
[Layer setFrame:frame2]; 
[layer addSublayer: customView.layer]; 

추신 :

그래서 기본적으로 아래

[self.view addSubview:customView]; 
[layer addSublayer:customView.layer]; //Causes crashes the minute the screen is touched 

코드입니다 내 현재 해결 방법은 UIImage UIView 변환하고 CALayer에 추가 할 수 있습니다.

벨로 사용자 정의 UIView의 코드입니다 :

- (id)initWithFrame:(CGRect)frame { 
self = [super initWithFrame:frame]; 
if (self) { 
    self.font = [UIFont fontWithName:ARCVIEW_DEFAULT_FONT_NAME size:ARCVIEW_DEFAULT_FONT_SIZE]; 
    self.text = @"Curva Style Label"; 

    NSLog(@"FONT = %@, TEXT = %@", self.font, self.text); 

    self.radius = ARCVIEW_DEFAULT_RADIUS; 
    self.showsGlyphBounds = NO; 
    self.showsLineMetrics = NO; 
    self.dimsSubstitutedGlyphs = NO; 
    self.color = [UIColor whiteColor]; 
    self.arcSize = ARCVIEW_DEFAULT_ARC_SIZE; 
    self.shiftH = self.shiftV = 0.0f; 
} 
return self; 

}

- (id)initWithFrame:(CGRect)frame font:(UIFont *)font text:(NSString *)text radius:(float)radius arcSize:(float)arcSize color:(UIColor *)color{ 

self = [super initWithFrame:frame]; 
if (self) { 
    self.font = font; 
    self.text = text; 
    self.radius = radius; 
    self.showsGlyphBounds = NO;// Border add for each Text 
    self.showsLineMetrics = NO; 
    self.dimsSubstitutedGlyphs = NO; 
    self.color = color; 
    self.arcSize = arcSize; 
    self.shiftH = self.shiftV = 0.0f; 
} 
return self; 

}

typedef struct GlyphArcInfo { 
CGFloat   width; 
CGFloat   angle; // in radians 

} GlyphArcInfo;

static void PrepareGlyphArcInfo(CTLineRef line, CFIndex glyphCount, GlyphArcInfo *glyphArcInfo, CGFloat arcSizeRad) 

{ NSArray를 runArray * = (NSArray를 *) CTLineGetGlyphRuns (행);

// Examine each run in the line, updating glyphOffset to track how far along the run is in terms of glyphCount. 
CFIndex glyphOffset = 0; 
for (id run in runArray) { 
    CFIndex runGlyphCount = CTRunGetGlyphCount((CTRunRef)run); 

     // Ask for the width of each glyph in turn. 
    CFIndex runGlyphIndex = 0; 
    for (; runGlyphIndex < runGlyphCount; runGlyphIndex++) { 
     glyphArcInfo[runGlyphIndex + glyphOffset].width = CTRunGetTypographicBounds((CTRunRef)run, CFRangeMake(runGlyphIndex, 1), NULL, NULL, NULL); 
    } 

    glyphOffset += runGlyphCount; 
} 

double lineLength = CTLineGetTypographicBounds(line, NULL, NULL, NULL); 

CGFloat prevHalfWidth = glyphArcInfo[0].width/2.0; 
glyphArcInfo[0].angle = (prevHalfWidth/lineLength) * arcSizeRad; 

    // Divide the arc into slices such that each one covers the distance from one glyph's center to the next. 
CFIndex lineGlyphIndex = 1; 
for (; lineGlyphIndex < glyphCount; lineGlyphIndex++) { 
    CGFloat halfWidth = glyphArcInfo[lineGlyphIndex].width/2.0; 
    CGFloat prevCenterToCenter = prevHalfWidth + halfWidth; 

    glyphArcInfo[lineGlyphIndex].angle = (prevCenterToCenter/lineLength) * arcSizeRad; 

    prevHalfWidth = halfWidth; 
} 

}

-(void)setText:(NSString *)text{ 
//[_string release]; 
_string = text; 

[self setNeedsDisplay]; 

}

-(void)setArcSize:(CGFloat)degrees{ 

_arcSize = degrees * M_PI/180.0; 

}

-(CGFloat)arcSize{ 
NSLog(@"arcSize %f",_arcSize * 180.0/M_PI); 

return _arcSize * 180.0/M_PI; 

}

- (void)drawRect:(CGRect)rect { 
    // Don't draw if we don't have a font or string 

NSLog(@"FONT = %@, TEXT = %@", self.font, self.text); 

if (self.font == NULL || self.text == NULL) 
    return; 

    // Initialize the text matrix to a known value 
CGContextRef context = UIGraphicsGetCurrentContext(); 
    //Reset the transformation 
    //Doing this means you have to reset the contentScaleFactor to 1.0 
CGAffineTransform t0 = CGContextGetCTM(context); 
CGContextSetShadowWithColor(context, CGSizeMake(self.xOffsetShadow, self.yOffsetShadow), self.blurShadow, self.shadowColor.CGColor); 

CGFloat xScaleFactor = t0.a > 0 ? t0.a : -t0.a; 
CGFloat yScaleFactor = t0.d > 0 ? t0.d : -t0.d; 
t0 = CGAffineTransformInvert(t0); 
if (xScaleFactor != 1.0 || yScaleFactor != 1.0) 
    t0 = CGAffineTransformScale(t0, xScaleFactor, yScaleFactor); 

CGContextConcatCTM(context, t0); 

CGContextSetTextMatrix(context, CGAffineTransformIdentity); 

if(ARCVIEW_DEBUG_MODE){ 
     // Draw a black background (debug) 
    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor); 
    CGContextFillRect(context, self.layer.bounds); 
} 

NSAttributedString *attStr = self.attributedString; 
CFAttributedStringRef asr = (__bridge CFAttributedStringRef)attStr; 
CTLineRef line = CTLineCreateWithAttributedString(asr); 
assert(line != NULL); 

CFIndex glyphCount = CTLineGetGlyphCount(line); 
if (glyphCount == 0) { 
    CFRelease(line); 
    return; 
} 

GlyphArcInfo * glyphArcInfo = (GlyphArcInfo*)calloc(glyphCount, sizeof(GlyphArcInfo)); 
PrepareGlyphArcInfo(line, glyphCount, glyphArcInfo, _arcSize); 

    // Move the origin from the lower left of the view nearer to its center. 
CGContextSaveGState(context); 

CGContextTranslateCTM(context, CGRectGetMidX(rect)+_shiftH, CGRectGetMidY(rect)+_shiftV); 

if(ARCVIEW_DEBUG_MODE){ 
     // Stroke the arc in red for verification. 
    CGContextBeginPath(context); 
    CGContextAddArc(context, 0.0, 0.0, self.radius, M_PI_2+_arcSize/2.0, M_PI_2-_arcSize/2.0, 1); 
    CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.0, 1.0); 
    CGContextStrokePath(context); 
} 

    // Rotate the context 90 degrees counterclockwise (per 180 degrees) 
CGContextRotateCTM(context, _arcSize/2.0); 

    // Now for the actual drawing. The angle offset for each glyph relative to the previous glyph has already been calculated; with that information in hand, draw those glyphs overstruck and centered over one another, making sure to rotate the context after each glyph so the glyphs are spread along a semicircular path. 

CGPoint textPosition = CGPointMake(0.0, self.radius); 
CGContextSetTextPosition(context, textPosition.x, textPosition.y); 

CFArrayRef runArray = CTLineGetGlyphRuns(line); 
CFIndex runCount = CFArrayGetCount(runArray); 

CFIndex glyphOffset = 0; 
CFIndex runIndex = 0; 
for (; runIndex < runCount; runIndex++) { 
    CTRunRef run = (CTRunRef)CFArrayGetValueAtIndex(runArray, runIndex); 
    CFIndex runGlyphCount = CTRunGetGlyphCount(run); 
    Boolean drawSubstitutedGlyphsManually = false; 
    CTFontRef runFont = CFDictionaryGetValue(CTRunGetAttributes(run), kCTFontAttributeName); 

     // Determine if we need to draw substituted glyphs manually. Do so if the runFont is not the same as the overall font. 
    if (self.dimsSubstitutedGlyphs && ![self.font isEqual:(__bridge UIFont *)runFont]) { 
     drawSubstitutedGlyphsManually = true; 
    } 

    CFIndex runGlyphIndex = 0; 
    for (; runGlyphIndex < runGlyphCount; runGlyphIndex++) { 
     CFRange glyphRange = CFRangeMake(runGlyphIndex, 1); 
     CGContextRotateCTM(context, -(glyphArcInfo[runGlyphIndex + glyphOffset].angle)); 

      // Center this glyph by moving left by half its width. 
     CGFloat glyphWidth = glyphArcInfo[runGlyphIndex + glyphOffset].width; 
     CGFloat halfGlyphWidth = glyphWidth/2.0; 
     CGPoint positionForThisGlyph = CGPointMake(textPosition.x - halfGlyphWidth, textPosition.y); 

      // Glyphs are positioned relative to the text position for the line, so offset text position leftwards by this glyph's width in preparation for the next glyph. 
     textPosition.x -= glyphWidth; 

     CGAffineTransform textMatrix = CTRunGetTextMatrix(run); 
     textMatrix.tx = positionForThisGlyph.x; 
     textMatrix.ty = positionForThisGlyph.y; 
     CGContextSetTextMatrix(context, textMatrix); 

     if (!drawSubstitutedGlyphsManually) { 
      CTRunDraw(run, context, glyphRange); 
     } 
     else { 
       // We need to draw the glyphs manually in this case because we are effectively applying a graphics operation by setting the context fill color. Normally we would use kCTForegroundColorAttributeName, but this does not apply as we don't know the ranges for the colors in advance, and we wanted demonstrate how to manually draw. 
      CGFontRef cgFont = CTFontCopyGraphicsFont(runFont, NULL); 
      CGGlyph glyph; 
      CGPoint position; 

      CTRunGetGlyphs(run, glyphRange, &glyph); 
      CTRunGetPositions(run, glyphRange, &position); 

      CGContextSetFont(context, cgFont); 
      CGContextSetFontSize(context, CTFontGetSize(runFont)); 
      CGContextSetRGBFillColor(context, 0.25, 0.25, 0.25, 0.5); 
      CGContextShowGlyphsAtPositions(context, &glyph, &position, 1); 

      CFRelease(cgFont); 
     } 

      // Draw the glyph bounds 
     if ((self.showsGlyphBounds) != 0) { 
      CGRect glyphBounds = CTRunGetImageBounds(run, context, glyphRange); 

      CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0); 
      CGContextStrokeRect(context, glyphBounds); 
     } 
      // Draw the bounding boxes defined by the line metrics 
     if ((self.showsLineMetrics) != 0) { 
      CGRect lineMetrics; 
      CGFloat ascent, descent; 

      CTRunGetTypographicBounds(run, glyphRange, &ascent, &descent, NULL); 

       // The glyph is centered around the y-axis 
      lineMetrics.origin.x = -halfGlyphWidth; 
      lineMetrics.origin.y = positionForThisGlyph.y - descent; 
      lineMetrics.size.width = glyphWidth; 
      lineMetrics.size.height = ascent + descent; 

      CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0); 
      CGContextStrokeRect(context, lineMetrics); 
     } 
    } 

    glyphOffset += runGlyphCount; 
} 

CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor); 
CGContextSetAlpha(context,0.0); 
CGContextFillRect(context, rect); 

CGContextRestoreGState(context); 

free(glyphArcInfo); 
CFRelease(line); 
01,235,

}

@synthesize font = _font; 
@synthesize text = _string; 
@synthesize radius = _radius; 
@synthesize color = _color; 
@synthesize arcSize = _arcSize; 
@synthesize shiftH = _shiftH; 
@synthesize shiftV = _shiftV; 
@synthesize shadowColor = _shadowColor; 
@synthesize xOffsetShadow = _xOffsetShadow; 
@synthesize blurShadow = _blurShadow; 
@synthesize yOffsetShadow = _yOffsetShadow; 

@dynamic attributedString; 

- (NSAttributedString *)attributedString { 
    // Create an attributed string with the current font and string. 
assert(self.font != nil); 
assert(self.text != nil); 

    // Create our attributes... 

    // font 
CTFontRef fontRef = CTFontCreateWithName((CFStringRef)self.font.fontName, self.font.pointSize, NULL); 

    // color 
CGColorRef colorRef = self.color.CGColor; 

    // pack it into attributes dictionary 

NSDictionary *attributesDict = [NSDictionary dictionaryWithObjectsAndKeys: 
           (__bridge id)fontRef, (id)kCTFontAttributeName, 
           colorRef, (id)kCTForegroundColorAttributeName, 
           nil]; 
assert(attributesDict != nil); 


    // Create the attributed string 
NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:self.text attributes:attributesDict]; 

return attrString; 

}

@end 
+0

충돌 로그를 표시합니다. 이 작업을 수행 한 경우 customview를 하위 뷰 * 및 *와 레이어로 추가하지 않아도됩니다. – Eiko

답변

6

당신은 정말 문제가 아니라 해결하기 위해 당신의 시도에 대한 문제에 대해 질문한다 : 당신은 추가 할 필요가 없습니다

[self.view addSubview:customView]; 
[layer addSublayer:customView.layer]; 
//Causes crashes the minute the screen is touched 

을 subview 및 레이어, 그냥 하위 뷰를 추가하십시오. 당신이하고있는 일은 무언가의 연결을 끊거나 무언가를 과밀하게 수정하고 원하지 않는 행동을 일으키는 것입니다.

레이어에 레이어를 추가하려면 레이어가 아닌보기로 작업하십시오. 뷰는 레이어를 소유하므로보기를 할당 해제 할 때 레이어의 연결을 끊거나 레이어를 유지하지 마십시오.

따라서 CALayer 하위 클래스를 만들고 현재 가지고있는 코드를 모두 drawInContext: 메소드로 이동하는 것이 가장 이상적입니다. 현재 사용중인 모든 코드가 CGContext에 그려 지므로 기본적으로 복사하여 붙여 넣을 수있는 것처럼 보입니다.

+0

대답은 완벽합니다. 감사! 하지만 사용자 정의 UIview를 CAlayer로 변환하는 방법을 알지 못합니다. 위의 사용자 정의보기 코드를 게시했습니다. 어떤 도움이라도 대단히 감사 할 것입니다. – user1752054

+0

왜 레이어가 필요한가요? – Wain

+0

videoComposition.animationTool = [AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer : videoLayer inLayer : compositionParentLayer]를 사용하여 동영상의 레이어를 그리기 때문에. – user1752054

관련 문제