2011-05-02 8 views
5

코코아 NSView에서 가운데 ​​정렬을 사용하여 새로운 라인 (\ n)으로 문자열을 그리려합니다. 예를 들어 내 문자열 인 경우 :코코아 뷰에서 중심 맞춤을 사용하여 텍스트를 그립니다.

가 는
NSString * str = @"this is a long line \n and \n this is also a long line"; 
가 나는 다소 표시이 싶습니다

:

여기
this is a long line 
     and 
this is also a long line 

는 NSView의의 drawRect 방법 안에 내 코드입니다 :

NSMutableParagraphStyle * paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy]; 

[paragraphStyle setAlignment:NSCenterTextAlignment]; 

NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line"; 

[mystr drawAtPoint:NSMakePoint(20, 20) withAttributes:attributes]; 

그것은 여전히를 그립니다 텍스트가 왼쪽 맞춤으로 표시됩니다. 이 코드의 문제점은 무엇입니까?

답변

13

다음 -[NSString drawAtPoint:withAttributes:] 상태의 문서 :

(수직 레이아웃 높이의) 폭 묘화 영역은 경계 사각형을 사용 drawInRect:withAttributes: 달리 무제한이다. 결과적으로이 메서드는 텍스트를 한 줄로 렌더링합니다.

너비는 무제한이므로 단락 맞춤을 무시하고 항상 왼쪽 맞춤 문자열을 렌더링합니다.

대신 -[NSString drawInRect:withAttributes:]을 사용해야합니다. 프레임을 허용하고 프레임의 너비가 있으므로 중앙 정렬을 계산할 수 있습니다. 예 :

NSMutableParagraphStyle * paragraphStyle = 
    [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease]; 
[paragraphStyle setAlignment:NSCenterTextAlignment]; 
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle 
    forKey:NSParagraphStyleAttributeName]; 

NSString * mystr = @"this is a long line \n and \n this is also a long line";  
NSRect strFrame = { { 20, 20 }, { 200, 200 } }; 

[mystr drawInRect:strFrame withAttributes:attributes]; 

원래 코드에 paragraphStyle이 누출됩니다.

+0

Garbage Collection을 사용하고 있다면 paragraphStyle이 계속 누출됩니까? – AmaltasCoder

+1

@AAmal 가비지 수집을 사용하는 경우 누출이 없습니다. –

관련 문제