- (void)drawRect:(CGRect)rect {
CGContextRef context=UIGraphicsGetCurrentContext();
//設置倒立
CGContextRotateCTM(context,M_PI);
//重新設置坐標 self.bounds獲取整個屏幕的區域。
CGContextTranslateCTM(context, -self.bounds.size.width,-self.bounds.size.height);
//CGContextScaleCTM(context, 1.0, -1.0);
CGRect imageRect=recti;
//畫底圖
CGContextDrawImage(context, imageRect, image);
//填充顏色
CGContextSetRGBStrokeColor(context,0.0,0.0,0.0,1.0);
CGContextFillRect(context,self.bounds);
CGRect ret=CGRectMake(0.0, 0.0, 180, 180);
//裁剪
CGContextClipToRect(context, ret);
//獲取裁剪區域
CGRect boudsc=CGContextGetClipBoundingBox(context);
int cleft = boudsc.origin.x;
int ctop = boudsc.origin.y;
int cwidth = boudsc.size.width;
int cheight = boudsc.size.height;
//畫出裁剪區域
CGContextDrawImage(context, self.bounds, image);
}
方法2:
UIImage *image=[UIImage imageNamed:@"**.png"];
創建矩形
根據矩形創建image
uiimageview.image=[UIimage imagewidthCGImage:CGImageCreateWidthImageInRect:([image CGImage],矩形)];
將image添加到imageview中
顯示view
參考:
NSLog( @" image width = %f,height = %f ",srcimg.size.width,srcimg.size.height);
UIImageView *imgview = [[UIImageView alloc] init];
imgview.frame = CGRectMake( 10, 150, 300, 220);
CGRect rect = CGRectMake( 0, 0, 300, 100);//要裁剪的圖片區域,按照原圖的像素大小來,超過原圖大小的邊自動適配
CGImageRef cgimg = CGImageCreateWithImageInRect([srcimg CGImage], rect);
imgview.image = [UIImage imageWithCGImage:cgimg];
CGImageRelease(cgimg);//用完一定要釋放,否則內存泄露
[self.view addSubview:imgview];