gpt4 book ai didi

iphone - 模拟NSImage绘制矩形:fromRect:operation:fraction with UIImage

转载 作者:行者123 更新时间:2023-12-03 21:12:25 24 4
gpt4 key购买 nike

我真的需要使用 UIImage 模拟 NSImage 的 drawInRect:fromRect:operation:fraction 的行为,我想知道什么是最好的方法或(更好),如果有人已经这样做并愿意分享代码。

我尝试使用 CGImageCreateWithImageInRect 执行此操作(请参阅最后的代码),但我没有得到预期的结果。请注意,代码实际上是在 mac 上测试的(我现在无法在 iPhone 上运行整个代码),所以我在从 NSImage 获取 CGImage 时可能会遇到一些问题

- (void)drawInRect:(CGRect)rect fromRect:(CGRect)fromRect alpha:(float)alpha {
CGContextRef context;
CGImageRef originalImageRef;
CGImageRef subimageRef;

#if ERMac
context=[[NSGraphicsContext currentContext] graphicsPort];

CGImageSourceRef source;

source = CGImageSourceCreateWithData((CFDataRef)[self TIFFRepresentation], NULL);
originalImageRef = CGImageSourceCreateImageAtIndex(source, 0, NULL);
CFRelease(source);
#else
context=UIGraphicsGetCurrentContext();
originalImageRef=CGImageRetain([self CGImage]);
#endif

subimageRef = CGImageCreateWithImageInRect (originalImageRef, fromRect);


CGContextDrawImage(context, rect, subimageRef);


if (subimageRef)
CGImageRelease(subimageRef);
if (originalImageRef)
CGImageRelease(originalImageRef);
}

最佳答案

我就是这样做的...

- (void)drawInRect:(CGRect)drawRect fromRect:(CGRect)fromRect operation:(CGBlendMode)blendMode fraction:(CGFloat)alpha
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextClipToRect(context, drawRect);

CGFloat xScale = (drawRect.size.width/fromRect.size.width);
CGFloat yScale = (drawRect.size.height/fromRect.size.height);

CGFloat scale = 1;
if([self respondsToSelector:@selector(scale)])
{
scale = self.scale;
}

CGFloat actualWidth = (xScale * self.size.width)*scale;
CGFloat actualHeight = (yScale * self.size.height)*scale;
CGFloat xInset = fromRect.origin.x * xScale;
CGFloat yInset = fromRect.origin.y * yScale;

// Take care of Y-axis inversion problem by translating the context on the y axis
CGContextTranslateCTM(context, 0, drawRect.size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(-xInset + drawRect.origin.x, -yInset + drawRect.origin.y, actualWidth, actualHeight), self.CGImage);

CGContextRestoreGState(context);
}

关于iphone - 模拟NSImage绘制矩形:fromRect:operation:fraction with UIImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2306644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com