2013-02-01 3 views
1

사진 앱을 개발 중입니다. 점에서 나는이코코아에서 스트레칭을 사용하여 NSImage 크기를 조정하는 방법

NSImage *fg_img = [[NSImage alloc]initWithData:[NSData dataWithContentsOfFile:filepath]]; 
     //NSData *imageData1 = [NSData dataWithContentsOfURL: [NSURL encryptedFileURLWithPath:str]] ; 
     NSImage *bg_img = [[NSImage alloc]initWithContentsOfURL:[NSURL encryptedFileURLWithPath:str]]; 



    NSImage *newImage ; 

    NSRect imageRect = NSMakeRect(0,0, fg_img.size.width+fg_img.size.width/5, fg_img.size.height+fg_img.size.height/5); 
    newImage = [[NSImage alloc] initWithSize: NSMakeSize(imageRect.size.width,imageRect.size.height)]; 
    NSRect fgrect = NSMakeRect(imageRect.size.width*0.03,imageRect.size.height*0.04, imageRect.size.width-imageRect.size.width/15.5, imageRect.size.height-imageRect.size.height/12); 

    [newImage lockFocus]; 

    [fg_img drawInRect:fgrect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; 
    [bg_img drawInRect:imageRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; 

    [newImage unlockFocus]; 

하지만 같은 그리기 사용하여 수행 한 NSImage에 대한 프레임을 만들 필요는 명확하지 ..

원래의 프레임 이미지

my original frame is

것은 나는 그것을 확장 할 때 출력은 enter image description here

위의 그림에서 t 프레임 이미지의 크기를 조정하면 해당 프레임이 변경되었습니다. 스케일링 할 때 프레임 이미지의 너비를 변경하지 않아도됩니다.

업데이트 :

하지만 코드 표시이

preview

처럼 내가 기본 이미지는 당신이 구 개 부분 이미지를 찾고 생각

답변

2

매우 얇은 될 큰 그림을 제공합니다. 9 개의 파트 이미지가 왼쪽과 오른쪽이 세로로 만 리사이즈됩니다. 위쪽과 아래쪽이 수평으로 만, 가운데가 독립적으로 축의 크기가 조정되고 모서리의 크기가 조정되지 않습니다.

_____________ 
|c | hor | c| 
|__|______|__| 
| |  | | 
|v | axes |v | 
|e |indep.|e | 
|r |  |r | 
|__|______|__| 
|c | hor |c | 
|__|______|__| 

애플은 같은 이미지를 그리는 데 도움이되는 방법 하세 : NSDrawNinePartImagehere 을하지만 이미지가 준비 될 필요가있다.

초기화 코드는 다음과 같다 :

static NSImage *baseImage = NULL; 
    static NSImage *topLeftCornerImage; 
    static NSImage *topEdgeImage; 
    static NSImage *topRightCornerImage; 
    static NSImage *leftEdgeImage; 
    static NSImage *centerImage; 
    static NSImage *rightEdgeImage; 
    static NSImage *bottomLeftCornerImage; 
    static NSImage *bottomEdgeImage; 
    static NSImage *bottomRightCornerImage; 

    + (void)initialize; 
    { 
     if (baseImage) return; 

     //46x46 


     baseImage = [NSImage imageNamed:@"badge.png"]; 

     topLeftCornerImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 22)]; 
     [topLeftCornerImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,22) 
        fromRect:NSMakeRect(0.0,24,22,22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [topLeftCornerImage unlockFocus]; 

     topEdgeImage = [[NSImage alloc] initWithSize:NSMakeSize(2, 22)]; 
     [topEdgeImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,2,22) 
        fromRect:NSMakeRect(22,24,2,22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [topEdgeImage unlockFocus]; 

     topRightCornerImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 22)]; 
     [topRightCornerImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,22) 
        fromRect:NSMakeRect(24,24,22,22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [topRightCornerImage unlockFocus]; 

     leftEdgeImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 2)]; 
     [leftEdgeImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,2) 
        fromRect:NSMakeRect(0,22,22,2) 
        operation:NSCompositeCopy fraction:1.0]; 
     [leftEdgeImage unlockFocus]; 

     centerImage = [[NSImage alloc] initWithSize:NSMakeSize(2, 2)]; 
     [centerImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,2,2) 
        fromRect:NSMakeRect(22,22,2,2) 
        operation:NSCompositeCopy fraction:1.0]; 
     [centerImage unlockFocus]; 

     rightEdgeImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 2)]; 
     [rightEdgeImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,2) 
        fromRect:NSMakeRect(24,24,22,2) 
        operation:NSCompositeCopy fraction:1.0]; 
     [rightEdgeImage unlockFocus]; 

     bottomLeftCornerImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 22)]; 
     [bottomLeftCornerImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,22) 
        fromRect:NSMakeRect(0,0,22,22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [bottomLeftCornerImage unlockFocus]; 

     bottomEdgeImage = [[NSImage alloc] initWithSize:NSMakeSize(2, 22)]; 
     [bottomEdgeImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0, 0, 2, 22) 
        fromRect:NSMakeRect(22, 0, 2, 22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [bottomEdgeImage unlockFocus]; 

     bottomRightCornerImage = [[NSImage alloc] initWithSize:NSMakeSize(22, 22)]; 
     [bottomRightCornerImage lockFocus]; 
     [baseImage drawInRect:NSMakeRect(0,0,22,22) 
        fromRect:NSMakeRect(24,0,22,22) 
        operation:NSCompositeCopy fraction:1.0]; 
     [bottomRightCornerImage unlockFocus]; 
    } 

drawingCode :

여기
NSDrawNinePartImage([self bounds], 
        topLeftCornerImage, topEdgeImage, topRightCornerImage, 
        leftEdgeImage, centerImage, rightEdgeImage, 
        bottomLeftCornerImage, bottomEdgeImage, bottomRightCornerImage, 
        NSCompositeSourceOver, 1.0, NO); 

가의 CALayer 기반 구 개 부분 이미지에 대한 내 실현의 또 다른 예이다 - NinePartLayer.

NinePartLayer.h

#import <Foundation/Foundation.h> 


@interface NinePartLayer : CALayer { 
@private 
    NSSize _blockSize; 
    NSMutableArray* layers; 
    NSMutableArray* _images; 
} 

+ (NinePartLayer*) layerWithImage:(NSImage*)aImage; 

@property (assign)NSSize blockSize; 
- (void) setImage:(NSImage*)aImage; 
@end 

NinePartLayer.m

#import "NinePartLayer.h" 

@interface NinePartLayer() 

@property (retain)NSMutableArray* layers; 
@property (retain)NSMutableArray* images; 

@end 

@implementation NinePartLayer 
@synthesize images = _images; 
@synthesize blockSize = _blockSize; 
@synthesize layers; 

+(NSImage*) imageFromImage:(NSImage *)anImage rect:(NSRect)aRect 
{ 
    @try { 
     NSPoint point = { -aRect.origin.x, -aRect.origin.y }; 
     NSImage *theImage = [[self alloc] initWithSize:aRect.size]; 
     [theImage lockFocus]; 
     [anImage compositeToPoint:point operation:NSCompositeCopy]; 
     [theImage unlockFocus]; 
     [theImage autorelease]; 
     return theImage; 
    } 
    @catch (NSException *exception) { 
     NSLog(@"%@",[exception description]); 
     return nil; 
    } 
} 

+ (NinePartLayer*) layerWithImage:(NSImage*)aImage 
{ 
    NinePartLayer* newLayer = [NinePartLayer layer]; 
    [newLayer setImage:aImage]; 
    return newLayer; 
} 

- (id)init { 
    self = [super init]; 
    if (self) { 
     self.layers = [NSMutableArray array]; 
     self.images = [NSMutableArray array]; 
    } 
    return self; 
} 

- (void) updateLayers 
{ 
    for (int i = 0; i < 3 && i < [self.images count]; ++i) { 
     NSMutableArray* row = [self.images objectAtIndex:i]; 
     for (int j = 0; j < 3 && j < [row count]; ++j) { 
      CALayer* item = [row objectAtIndex:j]; 
      float x,y,width,height; 
      if(i == 0){ 
       y = 0; 
       height = floorf(self.blockSize.height); 
      } else if(i == 1){ 
       y = ceilf(self.blockSize.height);  
       height = self.frame.size.height - 2*self.blockSize.height; 
      } else if(i == 2){ 
       y = self.frame.size.height - self.blockSize.height; 
       height = self.blockSize.height; 
      }; 
      if(j == 0){ 
       x = 0; 
       width = self.blockSize.width; 
      } else if(j == 1){ 
       x = self.blockSize.width; 
       width = self.frame.size.width - 2*self.blockSize.width; 
      } else if(j == 2){ 
       x = self.frame.size.width - self.blockSize.width; 
       width = self.blockSize.width; 
      }; 

      item.frame = CGRectMake(x, y, width, height); 

      float delta=0; 

      if((i==1)&&(j==0)) 
      { 
       item.frame = CGRectMake(x, y-delta, width+delta, height+2*delta); 
      } 

      if((i==2)&&(j==1)) 
      { 
       item.frame = CGRectMake(x-delta, y-delta, width+2*delta, height+delta); 
      } 

      if((i==1)&&(j==2)) 
      { 
       item.frame = CGRectMake(x-delta, y-delta, width+delta, height+2*delta); 
      } 

      if((i==0)&&(j==1)) 
      { 
       item.frame = CGRectMake(x-delta, y, width+2*delta, height+delta); 
      } 
     } 
    } 
} 

- (void) setImage:(NSImage*)aImage 
{ 
    for(int i = 0; i < [self.layers count]; ++i) 
     [[self.layers objectAtIndex:i] removeFromSuperlayer]; 

    [self.layers removeAllObjects]; 

    self.images = [NSMutableArray array]; 
    self.layers = [NSMutableArray array]; 
    if(!aImage) 
     return; 

    for (int i = 0; i < 3; ++i) { 
     NSMutableArray* row = [NSMutableArray array]; 
     for (int j = 0; j < 3; ++j) { 
      NSImage* img = [NSImage imageFromImage:aImage 
               rect:NSMakeRect((float)j/3.0*[aImage size].width, 
                   (float)i/3.0*[aImage size].height, 
                   1.0/3.0*[aImage size].width, 
                   1.0/3.0*[aImage size].height)]; 
      self.blockSize = NSMakeSize(1.0/3.0*[aImage size].width, 1.0/3.0*[aImage size].height); 

      CALayer* item = [CALayer layer]; 
      [item performSelectorOnMainThread:@selector(setContents:) withObject:img waitUntilDone:NO]; 
      [item performSelectorOnMainThread:@selector(setContentsGravity:) withObject:kCAGravityResize waitUntilDone:NO]; 
      [self performSelectorOnMainThread:@selector(addSublayer:) withObject:item waitUntilDone:NO]; 
      [row addObject:item]; 
      [self.layers addObject:item]; 
     } 
     [self.images addObject:row]; 
    } 
    [self performSelectorOnMainThread:@selector(updateLayers) withObject:nil waitUntilDone:NO]; 
} 

- (void) setFrame:(CGRect)frame 
{ 
    [super setFrame:frame]; 
    [self updateLayers]; 
} 

- (void) setBounds:(CGRect)bounds 
{ 
    [super setBounds:bounds]; 
    [self updateLayers]; 
} 

- (void) setPosition:(CGPoint)position 
{ 
    [super setPosition:position]; 
    [self updateLayers]; 
} 

- (void)dealloc { 
    self.layers = nil; 
    self.images = nil; 
    [super dealloc]; 
} 
@end 

사용 :

NinePartLayer * pageContainerShadowlayer=[NinePartLayer layerWithImage:[NSImage imageNamed:@"drop_shadow.png"]]; 
    pageContainerShadowlayer.frame=[mainView layer].bounds; 
    pageContainerShadowlayer.autoresizingMask=kCALayerWidthSizable | kCALayerHeightSizable; 
    [[rootView layer] insertSublayer:pageContainerShadowlayer atIndex:3]; 
+0

코드가 명확하지 않습니다. 내 질문이 업데이트되었습니다. – NewStack

+0

첫 번째 예제를 사용했습니다 – NewStack

+0

이제 모든게 괜찮습니까? – Remizorrr

0

당신이 NSDrawNinePartImage을 생각 해 봤나? 시각적 인 이음새가없고 모서리와 가장자리 이미지를 늘리지 않고 제시 한 배열로 9 개의 이미지 (네 모서리, 네 모서리, 가운데)를 그리기 위해 특별히 고안된 기능입니다.

+0

IIRC를 통해 중심이 찌그러 지거나 뻗어 있습니다. D –

+1

아, 예 - NSDrawNinePartImage가 중심 이미지를 바둑판 식으로 배열합니다. 그것은 프레임에 맞게 늘어나지 않습니다. 질문자가 이미지 크기 주변의 프레임 크기를 계산하고 위 또는 아래로 크기를 조정하지 않으려는 경우에만 여전히 작동 할 수 있습니다. –

관련 문제