コード例 #1
0
ファイル: tilecachecg.cpp プロジェクト: alilloyd/livecode
bool MCTileCacheCoreGraphicsCompositor_BeginLayer(void *p_context, const MCRectangle& p_clip, uint32_t p_opacity, uint32_t p_ink)
{
	MCTileCacheCoreGraphicsCompositorContext *self;
	self = (MCTileCacheCoreGraphicsCompositorContext *)p_context;
	
	CGContextSaveGState(self -> cgcontext);
	
	// MW-2012-09-18: [[ Bug 10202 ]] If the ink is no-op then ensure nothing happens.
	if (p_ink == GXnoop)
		CGContextClipToRect(self -> cgcontext, CGRectZero);
	else
	{
		CGContextClipToRect(self -> cgcontext, CGRectMake(p_clip . x, self -> viewport_height - (p_clip . y + p_clip . height), p_clip . width, p_clip . height));
		CGContextSetAlpha(self -> cgcontext, p_opacity / 255.0);
		
		CGBlendMode t_blend_mode;
		switch(p_ink)
		{
			case GXblendMultiply:
				t_blend_mode = kCGBlendModeMultiply;
				break;
			case GXblendScreen: 
				t_blend_mode = kCGBlendModeScreen;
				break;
			case GXblendOverlay: 
				t_blend_mode = kCGBlendModeOverlay;
				break;
			case GXblendDarken: 
				t_blend_mode = kCGBlendModeDarken;
				break;
			case GXblendLighten: 
				t_blend_mode = kCGBlendModeLighten;
				break;
			case GXblendDodge: 
				t_blend_mode = kCGBlendModeColorDodge;
				break;
			case GXblendBurn: 
				t_blend_mode = kCGBlendModeColorBurn;
				break;
			case GXblendSoftLight: 
				t_blend_mode = kCGBlendModeSoftLight;
				break;
			case GXblendHardLight: 
				t_blend_mode = kCGBlendModeHardLight;
				break;
			case GXblendDifference: 
				t_blend_mode = kCGBlendModeDifference;
				break;
			case GXblendExclusion: 
				t_blend_mode = kCGBlendModeExclusion;
				break;
			default:
				t_blend_mode = kCGBlendModeNormal;
				break;
		}
		CGContextSetBlendMode(self -> cgcontext, t_blend_mode);
	}
	
	return true;
}
コード例 #2
0
void PDFDocumentImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator op)
{
    if (!m_document || m_currentPage == -1)
        return;

    context->save();

    context->setCompositeOperation(op);

    float hScale = dstRect.width() / srcRect.width();
    float vScale = dstRect.height() / srcRect.height();

    // Scale and translate so the document is rendered in the correct location,
    // including accounting for the fact that a GraphicsContext is always flipped
    // and doing appropriate flipping.
    CGContextTranslateCTM(context->platformContext(), dstRect.x() - srcRect.x() * hScale, dstRect.y() - srcRect.y() * vScale);
    CGContextScaleCTM(context->platformContext(), hScale, vScale);
    CGContextScaleCTM(context->platformContext(), 1, -1);
    CGContextTranslateCTM(context->platformContext(), 0, -srcRect.height());
    CGContextClipToRect(context->platformContext(), CGRectIntegral(srcRect));

    // Rotate translate image into position according to doc properties.
    adjustCTM(context);

    // Media box may have non-zero origin which we ignore. Pass 1 for the page number.
    CGContextDrawPDFDocument(context->platformContext(), FloatRect(FloatPoint(), m_mediaBox.size()),
        m_document, m_currentPage + 1);
    
    context->restore();

    if (imageObserver())
        imageObserver()->didDraw(this);
}
コード例 #3
0
ファイル: osxstack.cpp プロジェクト: Bjoernke/livecode
static void MCMacRenderBitsToCG(CGContextRef p_target, CGRect p_area, const void *p_bits, uint32_t p_stride, bool p_has_alpha)
{
	CGColorSpaceRef t_colorspace;
	t_colorspace = CGColorSpaceCreateDeviceRGB();
	if (t_colorspace != nil)
	{
		CGBitmapInfo t_bitmap_info;
		t_bitmap_info = kCGBitmapByteOrder32Host;
		t_bitmap_info |= p_has_alpha ? kCGImageAlphaPremultipliedFirst : kCGImageAlphaNoneSkipFirst;
		
		CGContextRef t_cgcontext;
		t_cgcontext = CGBitmapContextCreate((void *)p_bits, p_area . size . width, p_area . size . height, 8, p_stride, t_colorspace, t_bitmap_info);
		if (t_cgcontext != nil)
		{
			CGImageRef t_image;
			t_image = CGBitmapContextCreateImage(t_cgcontext);
			CGContextRelease(t_cgcontext);
			
			if (t_image != nil)
			{
				CGContextClipToRect((CGContextRef)p_target, p_area);
				CGContextDrawImage((CGContextRef)p_target, p_area, t_image);
				CGImageRelease(t_image);
			}
		}
		
		CGColorSpaceRelease(t_colorspace);
	}
}
コード例 #4
0
ファイル: GraphicsContextCG.cpp プロジェクト: dslab-epfl/warr
void GraphicsContext::fillRect(const FloatRect& rect)
{
    if (paintingDisabled())
        return;

    CGContextRef context = platformContext();

    if (m_state.fillGradient) {
        CGContextSaveGState(context);
        CGContextConcatCTM(context, m_state.fillGradient->gradientSpaceTransform());
        if (hasShadow()) {
            CGLayerRef layer = CGLayerCreateWithContext(context, CGSizeMake(rect.width(), rect.height()), 0);
            CGContextRef layerContext = CGLayerGetContext(layer);
            m_state.fillGradient->paint(layerContext);
            CGContextDrawLayerAtPoint(context, CGPointMake(rect.left(), rect.top()), layer);
            CGLayerRelease(layer);
        } else {
            CGContextClipToRect(context, rect);
            m_state.fillGradient->paint(this);
        }
        CGContextRestoreGState(context);
        return;
    }

    if (m_state.fillPattern)
        applyFillPattern();
    CGContextFillRect(context, rect);
}
コード例 #5
0
ファイル: GraphicsContextCG.cpp プロジェクト: dslab-epfl/warr
void GraphicsContext::clip(const FloatRect& rect)
{
    if (paintingDisabled())
        return;
    CGContextClipToRect(platformContext(), rect);
    m_data->clip(rect);
}
コード例 #6
0
void PDFDocumentImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, ColorSpace, CompositeOperator op, BlendMode)
{
    if (!m_document || m_currentPage == -1)
        return;

    {
        GraphicsContextStateSaver stateSaver(*context);

        context->setCompositeOperation(op);

        float hScale = dstRect.width() / srcRect.width();
        float vScale = dstRect.height() / srcRect.height();

        // Scale and translate so the document is rendered in the correct location,
        // including accounting for the fact that a GraphicsContext is always flipped
        // and doing appropriate flipping.
        CGContextTranslateCTM(context->platformContext(), dstRect.x() - srcRect.x() * hScale, dstRect.y() - srcRect.y() * vScale);
        CGContextScaleCTM(context->platformContext(), hScale, vScale);
        CGContextScaleCTM(context->platformContext(), 1, -1);
        CGContextTranslateCTM(context->platformContext(), 0, -srcRect.height());
        CGContextClipToRect(context->platformContext(), CGRectIntegral(srcRect));

        // Rotate translate image into position according to doc properties.
        adjustCTM(context);

        CGContextTranslateCTM(context->platformContext(), -m_mediaBox.x(), -m_mediaBox.y());
        CGContextDrawPDFPage(context->platformContext(), CGPDFDocumentGetPage(m_document, m_currentPage + 1));
    }

    if (imageObserver())
        imageObserver()->didDraw(this);
}
コード例 #7
0
void MacVegaPrinterListener::SetClipRect(const OpRect& clip)
{
	CGContextRestoreGState(m_ctx);
	CGContextSaveGState(m_ctx);
	CGContextClipToRect(m_ctx, CGRectMake(clip.x, m_winHeight-(clip.y+clip.height), clip.width, clip.height));
	CGContextSetRGBFillColor(m_ctx, m_red, m_green, m_blue, m_alpha);
	CGContextSetRGBStrokeColor(m_ctx, m_red, m_green, m_blue, m_alpha);
}
コード例 #8
0
 void updateHandle(Handle hndl, const SkMatrix& ctm, const SkIRect& clip) override {
     CGContextRef cg = (CGContextRef)hndl;
     
     CGContextRestoreGState(cg);
     CGContextSaveGState(cg);
     CGContextClipToRect(cg, CGRectMake(clip.x(), clip.y(), clip.width(), clip.height()));
     CGContextConcatCTM(cg, matrix_to_transform(cg, ctm));
 }
コード例 #9
0
ファイル: ShadeRect.c プロジェクト: fruitsamples/CalendarView
// -----------------------------------------------------------------------------
//	ShadeRectColor
// -----------------------------------------------------------------------------
//
OSStatus ShadeRectColor(
	const CGRGB*		inStartColor,
	const CGRGB*		inEndColor,
	const HIRect*		inRect,
	CGContextRef		inContext )
{
	OSStatus			err = noErr;
	CGColorSpaceRef		colorSpace;
	CGFunctionCallbacks	callbacks = { 0, ColorGradientEvaluate, NULL };
	CGFunctionRef		function;
	CGShadingRef		shading;
	ColorShadeData		data;
	
	// Warning: this stuff is sitting on the stack.  Be careful if you move
	// the shading code around.
	data.start = *inStartColor;
	data.range.red = inEndColor->red - inStartColor->red;
	data.range.green = inEndColor->green - inStartColor->green;
	data.range.blue = inEndColor->blue - inStartColor->blue;
	
	CGContextSaveGState( inContext );
	CGContextClipToRect( inContext, *inRect );

	colorSpace = CGColorSpaceCreateDeviceRGB();
	require_action( colorSpace != NULL, CantCreateColorSpace, err = memFullErr );

	function = CGFunctionCreate(
			&data,			// info
			1,				// domainDimension
			NULL,			// input domain NULL == no range clipping
			4,				// rangeDimension,
			NULL,			// output domain NULL == no range clipping
			&callbacks );	// CGFunctionCallbacks
	require_action( function != NULL, CantCreateFunction, err = memFullErr );

	shading = CGShadingCreateAxial(
			colorSpace,
			inRect->origin,	// start
			CGPointMake( CGRectGetMinX( *inRect ), CGRectGetMaxY( *inRect ) ),	// end
			function,
			false,			// extendStart
			false );		// extendEnd
	require_action( colorSpace != NULL, CantCreateShading, err = memFullErr );

	CGContextDrawShading( inContext, shading);

CantCreateFunction:
	CGShadingRelease( shading );

CantCreateShading:
	CGColorSpaceRelease( colorSpace );

CantCreateColorSpace:
	CGContextRestoreGState( inContext );
	
	return err;
}
コード例 #10
0
void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height, ExceptionCode& ec)
{
    ec = 0;

    if (!(width >= 0 && height >= 0)) {
        ec = INDEX_SIZE_ERR;
        return;
    }

    GraphicsContext* c = drawingContext();
    if (!c)
        return;
    // FIXME: Do this through platform-independent GraphicsContext API.
#if PLATFORM(CG)
    CGRect rect = CGRectMake(x, y, width, height);

    willDraw(rect);

    if (state().m_fillStyle->gradient()) {
        // Shading works on the entire clip region, so convert the rect to a clip.
        c->save();
        CGContextClipToRect(c->platformContext(), rect);
        CGContextDrawShading(c->platformContext(), state().m_fillStyle->gradient()->platformShading());        
        c->restore();
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
        CGContextFillRect(c->platformContext(), rect);
    }
#elif PLATFORM(QT)
    QRectF rect(x, y, width, height);
    willDraw(rect);
    QPainter* p = static_cast<QPainter*>(c->platformContext());
    if (state().m_fillStyle->gradient()) {
        p->fillRect(rect, QBrush(*(state().m_fillStyle->gradient()->platformShading())));
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
        p->fillRect(rect, p->brush());
    }
#elif PLATFORM(CAIRO)
    FloatRect rect(x, y, width, height);
    willDraw(rect);
    cairo_t* cr = c->platformContext();
    cairo_save(cr);
    if (state().m_fillStyle->gradient()) {
        cairo_set_source(cr, state().m_fillStyle->gradient()->platformShading());
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
    }
    cairo_rectangle(cr, x, y, width, height);
    cairo_fill(cr);
    cairo_restore(cr);
#endif
}
コード例 #11
0
ファイル: cgdrawcontext.cpp プロジェクト: DaniM/lyngo
//-----------------------------------------------------------------------------
void CGDrawContext::drawBitmap (CBitmap* bitmap, const CRect& inRect, const CPoint& inOffset, float alpha)
{
	if (bitmap == 0 || alpha == 0.f)
		return;
	CGBitmap* cgBitmap = bitmap->getPlatformBitmap () ? dynamic_cast<CGBitmap*> (bitmap->getPlatformBitmap ()) : 0;
	CGImageRef image = cgBitmap ? cgBitmap->getCGImage () : 0;
	if (image)
	{
		CGContextRef context = beginCGContext (false, true);
		if (context)
		{
			CRect rect (inRect);
			rect.makeIntegral ();
			CPoint offset (inOffset);
			offset.makeIntegral ();

			CGContextSetAlpha (context, (CGFloat)alpha*currentState.globalAlpha);

			CGRect dest;
			dest.origin.x = rect.left - offset.h;
			dest.origin.y = -(rect.top) - (bitmap->getHeight () - offset.v);
			dest.size.width = cgBitmap->getSize ().x;
			dest.size.height = cgBitmap->getSize ().y;
			
			CGRect clipRect2;
			clipRect2.origin.x = rect.left;
			clipRect2.origin.y = -(rect.top) - rect.height ();
			clipRect2.size.width = rect.width (); 
			clipRect2.size.height = rect.height ();
		
			CGContextClipToRect (context, clipRect2);

			CGLayerRef layer = cgBitmap->getCGLayer ();
			if (layer == 0)
			{
				BitmapDrawCountMap::iterator it = bitmapDrawCount.find (cgBitmap);
				if (it == bitmapDrawCount.end ())
				{
					bitmapDrawCount.insert (std::pair<CGBitmap*, int32_t> (cgBitmap, 1));
					CGContextDrawImage (context, dest, image);
				}
				else
				{
					it->second++;
					layer = cgBitmap->createCGLayer (context);
				}
			}
			if (layer)
			{
				CGContextDrawLayerInRect (context, dest, layer);
			}

			releaseCGContext (context);
		}
	}
}
コード例 #12
0
ファイル: ioscanvas.cpp プロジェクト: huangzongwu/touchvg
void GiCanvasIos::_clipBoxChanged(const RECT_2D& clipBox)
{
    if (m_draw->getContext())
    {
        CGRect rect = CGRectMake(clipBox.left, clipBox.top, 
                                 clipBox.right - clipBox.left, 
                                 clipBox.bottom - clipBox.top);
        CGContextClipToRect(m_draw->getContext(), rect);
    }
}
コード例 #13
0
ファイル: ImageCG.cpp プロジェクト: acss/owb-mirror
void BitmapImage::draw(GraphicsContext* ctxt, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOp)
{
    CGImageRef image = frameAtIndex(m_currentFrame);
    if (!image) // If it's too early we won't have an image yet.
        return;
    
    if (mayFillWithSolidColor()) {
        fillWithSolidColor(ctxt, destRect, solidColor(), compositeOp);
        return;
    }

    CGContextRef context = ctxt->platformContext();
    ctxt->save();

    // If the source rect is a subportion of the image, then we compute an inflated destination rect that will hold the entire image
    // and then set a clip to the portion that we want to display.
    CGSize selfSize = size();
    FloatRect adjustedDestRect = destRect;
    if (srcRect.width() != selfSize.width || srcRect.height() != selfSize.height) {
        // A subportion of the image is drawing.  Adjust the destination rect to
        // account for this.
        float xScale = srcRect.width() / destRect.width();
        float yScale = srcRect.height() / destRect.height();
        
        adjustedDestRect.setLocation(FloatPoint(destRect.x() - srcRect.x() / xScale, destRect.y() - srcRect.y() / yScale));
        adjustedDestRect.setSize(FloatSize(size().width() / xScale, size().height() / yScale));
        
        CGContextClipToRect(context, destRect);
    }

    // If the image is only partially loaded, then shrink the destination rect that we're drawing into accordingly.
    float currHeight = CGImageGetHeight(image);
    if (currHeight < selfSize.height)
        adjustedDestRect.setHeight(adjustedDestRect.height() * currHeight / selfSize.height);

    // Flip the coords.
    ctxt->setCompositeOperation(compositeOp);
    CGContextTranslateCTM(context, adjustedDestRect.x(), adjustedDestRect.bottom());
    CGContextScaleCTM(context, 1, -1);
    adjustedDestRect.setLocation(FloatPoint());

    // Draw the image.
    CGContextDrawImage(context, adjustedDestRect, image);
        
    ctxt->restore();
    
    startAnimation();

    if (imageObserver())
        imageObserver()->didDraw(this);
}
コード例 #14
0
void CanvasRenderingContext2D::fillRect(float x, float y, float width, float height)
{
    if (!validateRectForCanvas(x, y, width, height))
        return;

    GraphicsContext* c = drawingContext();
    if (!c)
        return;

    FloatRect rect(x, y, width, height);
    willDraw(rect);

    // FIXME: Do this through platform-independent GraphicsContext API.
#if PLATFORM(CG)
    if (state().m_fillStyle->canvasGradient()) {
        // Shading works on the entire clip region, so convert the rect to a clip.
        c->save();
        CGContextClipToRect(c->platformContext(), rect);
        CGContextDrawShading(c->platformContext(), state().m_fillStyle->canvasGradient()->gradient().platformGradient());        
        c->restore();
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
        CGContextFillRect(c->platformContext(), rect);
    }
#elif PLATFORM(QT)
    QPainter* p = static_cast<QPainter*>(c->platformContext());
    if (state().m_fillStyle->canvasGradient()) {
        p->fillRect(rect, QBrush(*(state().m_fillStyle->canvasGradient()->gradient().platformGradient())));
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
        p->fillRect(rect, p->brush());
    }
#elif PLATFORM(CAIRO) && !PLATFORM(BAL)
    cairo_t* cr = c->platformContext();
    cairo_save(cr);
    if (state().m_fillStyle->canvasGradient()) {
        cairo_set_source(cr, state().m_fillStyle->canvasGradient()->gradient().platformGradient());
    } else {
        if (state().m_fillStyle->pattern())
            applyFillPattern();
    }
    cairo_rectangle(cr, x, y, width, height);
    cairo_fill(cr);
    cairo_restore(cr);
#elif PLATFORM(BAL)
    //FIXME
    notImplemented();
#endif
}
コード例 #15
0
ファイル: ImageBufferCG.cpp プロジェクト: TigerLau1985/webkit
void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem coordinateSystem)
{
    if (!context().isAcceleratedContext()) {
        IntRect scaledSourceRect = sourceRect;
        IntSize scaledSourceSize = sourceSize;
        if (coordinateSystem == LogicalCoordinateSystem) {
            scaledSourceRect.scale(m_resolutionScale);
            scaledSourceSize.scale(m_resolutionScale);
        }

        m_data.putData(source, scaledSourceSize, scaledSourceRect, destPoint, internalSize(), false, multiplied == Unmultiplied, 1);
        return;
    }

#if USE(IOSURFACE_CANVAS_BACKING_STORE)
    // Make a copy of the source to ensure the bits don't change before being drawn
    IntSize sourceCopySize(sourceRect.width(), sourceRect.height());
    // FIXME (149431): Should this ImageBuffer be unconditionally unaccelerated? Making it match the context seems to break putData().
    std::unique_ptr<ImageBuffer> sourceCopy = ImageBuffer::create(sourceCopySize, Unaccelerated, 1, ColorSpaceDeviceRGB);
    if (!sourceCopy)
        return;

    sourceCopy->m_data.putData(source, sourceSize, sourceRect, IntPoint(-sourceRect.x(), -sourceRect.y()), sourceCopy->internalSize(), sourceCopy->context().isAcceleratedContext(), multiplied == Unmultiplied, 1);

    // Set up context for using drawImage as a direct bit copy
    CGContextRef destContext = context().platformContext();
    CGContextSaveGState(destContext);
    if (coordinateSystem == LogicalCoordinateSystem)
        CGContextConcatCTM(destContext, AffineTransform(wkGetUserToBaseCTM(destContext)).inverse());
    else
        CGContextConcatCTM(destContext, AffineTransform(CGContextGetCTM(destContext)).inverse());
    CGContextResetClip(destContext);
    CGContextSetInterpolationQuality(destContext, kCGInterpolationNone);
    CGContextSetAlpha(destContext, 1.0);
    CGContextSetBlendMode(destContext, kCGBlendModeCopy);
    CGContextSetShadowWithColor(destContext, CGSizeZero, 0, 0);

    // Draw the image in CG coordinate space
    FloatSize scaledDestSize = scaleSizeToUserSpace(coordinateSystem == LogicalCoordinateSystem ? logicalSize() : internalSize(), m_data.backingStoreSize, internalSize());
    IntPoint destPointInCGCoords(destPoint.x() + sourceRect.x(), scaledDestSize.height() - (destPoint.y() + sourceRect.y()) - sourceRect.height());
    IntRect destRectInCGCoords(destPointInCGCoords, sourceCopySize);
    CGContextClipToRect(destContext, destRectInCGCoords);

    RetainPtr<CGImageRef> sourceCopyImage = sourceCopy->copyNativeImage();
    FloatRect backingStoreInDestRect = FloatRect(FloatPoint(destPointInCGCoords.x(), destPointInCGCoords.y() + sourceCopySize.height() - (int)CGImageGetHeight(sourceCopyImage.get())), FloatSize(CGImageGetWidth(sourceCopyImage.get()), CGImageGetHeight(sourceCopyImage.get())));
    CGContextDrawImage(destContext, backingStoreInDestRect, sourceCopyImage.get());
    CGContextRestoreGState(destContext);
#endif
}
コード例 #16
0
void CGImageLuminanceSource::init (CGImageRef cgimage, int left, int top, int width, int height) {
    data_ = 0;
    image_ = cgimage;
    left_ = left;
    top_ = top;
    width_ = width;
    height_ = height;
    dataWidth_ = (int)CGImageGetWidth(image_);
    dataHeight_ = (int)CGImageGetHeight(image_);

    if (left_ + width_ > dataWidth_ ||
        top_ + height_ > dataHeight_ ||
        top_ < 0 ||
        left_ < 0) {
        throw IllegalArgumentException("Crop rectangle does not fit within image data.");
    }

    CGColorSpaceRef space = CGImageGetColorSpace(image_);
    CGColorSpaceModel model = CGColorSpaceGetModel(space);

    if (model != kCGColorSpaceModelMonochrome || CGImageGetBitsPerComponent(image_) != 8 || CGImageGetBitsPerPixel(image_) != 8) {
        CGColorSpaceRef gray = CGColorSpaceCreateDeviceGray();
        
        CGContextRef ctx = CGBitmapContextCreate(0, width, height, 8, width, gray, kCGImageAlphaNone);
        
        CGColorSpaceRelease(gray);

        if (top || left) {
            CGContextClipToRect(ctx, CGRectMake(0, 0, width, height));
        }

        CGContextDrawImage(ctx, CGRectMake(-left, -top, width, height), image_);
    
        image_ = CGBitmapContextCreateImage(ctx);

        bytesPerRow_ = width;
        top_ = 0;
        left_ = 0;
        dataWidth_ = width;
        dataHeight_ = height;

        CGContextRelease(ctx);
    } else {
        CGImageRetain(image_);
    }

    CGDataProviderRef provider = CGImageGetDataProvider(image_);
    data_ = CGDataProviderCopyData(provider);
}
コード例 #17
0
void doSimpleCGLayer(CGContextRef context)
{
    int i,j;
    CGSize s;
    // Create the layer.
    CGLayerRef layer = createCGLayerForDrawing(context);
    if(layer == NULL){
		fprintf(stderr, "Couldn't create layer!\n");
		return;
    }
    
    // Get the size of the layer created.
    s = CGLayerGetSize(layer);
    
    // Clip to a rect that corresponds to
    // a grid of 8x8 layer objects.
    CGContextClipToRect(context, CGRectMake(0, 0, 8*s.width, 8*s.height));
    
    // Paint 8 rows of layer objects.
    for(j = 0 ; j < 8 ; j++){
		CGContextSaveGState(context);
			// Paint 4 columns of layer objects, moving
			// across the drawing canvas by skipping a
			// square on the grid each time across.
			for(i = 0 ; i < 4 ; i++){
				// Draw the layer at the current origin.
				CGContextDrawLayerAtPoint(context, 
					CGPointZero, 
					layer);
				// Translate across two layer widths.
				CGContextTranslateCTM(context, 2*s.width, 0);
			}
		CGContextRestoreGState(context);
		// Translate to the left one layer width on
		// even loop counts and to the right one
		// layer width on odd loop counts. Each
		// time through the outer loop, translate up
		// one layer height.
		CGContextTranslateCTM(context, 
			(j % 2) ? s.width: -s.width, 
			s.height);
    }
    // Release the layer when done drawing with it.
    CGLayerRelease(layer);
}
コード例 #18
0
ファイル: devQuartz.c プロジェクト: Vladimir84/rcc
static void 	Quartz_Clip(double x0, double x1, double y0, double y1,
		     	NewDevDesc *dd)
{
    QuartzDesc *xd = (QuartzDesc*)dd->deviceSpecific;
	float x, y, width, height;

    if (x0 < x1) {
		x = x0;
		width = (float)(x1 -x0);
    }
    else {
		x = x1;
		width = (float)(x0 -x1);
    }

    if (y0 < y1) {
		y = y0;
		height = (float)(y1 -y0);
    }
    else {
		y = y1;
		height = (float)(y0-y1);
    }

/*  
	Clipping on Quartz works on intersections of paths.
	RestoreGState must be called before clipping. This
	ensures that the clipping path is cleared.
	As R makes subsequent calls of Clip() we need to
	1. Save the GState before Clipping
	2. Clipping
	3. all the subsequent drawings will be in the clipped
	   rectangle
	4. on the next device->Clip() call we RestoreGState to
	   clear the clipping path

	See Apple's Technical Q&A QA1050 "Turn Off Core Graphics Clipping"
	S.M.I.
*/	   
	CGContextRestoreGState(GetContext(xd)); 
	
	CGContextSaveGState( GetContext(xd) );
	CGContextClipToRect( GetContext(xd), CGRectMake(x, y, width, height) );
	
}
コード例 #19
0
ファイル: GraphicsContextCG.cpp プロジェクト: dslab-epfl/warr
void GraphicsContext::clip(const Path& path)
{
    if (paintingDisabled())
        return;
    CGContextRef context = platformContext();

    // CGContextClip does nothing if the path is empty, so in this case, we
    // instead clip against a zero rect to reduce the clipping region to
    // nothing - which is the intended behavior of clip() if the path is empty.    
    if (path.isEmpty())
        CGContextClipToRect(context, CGRectZero);
    else {
        CGContextBeginPath(context);
        CGContextAddPath(context, path.platformPath());
        CGContextClip(context);
    }
    m_data->clip(path);
}
コード例 #20
0
ファイル: TIPGradient.c プロジェクト: samiamwork/Questionable
void TIPGradientRadialFillRect( CGContextRef theContext, TIPGradientRef theGradient, CGRect theRect, CGPoint center, float radius)
{
    CGPoint startPoint = center;
    CGPoint endPoint = center;
    float startRadius = 1.0f;
    float endRadius = radius;

    // CoreGraphics Calls
    CGContextSaveGState(theContext);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGShadingRef myCGShading = CGShadingCreateRadial(colorSpace,startPoint,startRadius,endPoint,endRadius,theGradient->gradientFunction,FALSE,FALSE);

    CGContextClipToRect(theContext,theRect);
    CGContextDrawShading(theContext,myCGShading);

    CGShadingRelease(myCGShading);
    CGColorSpaceRelease(colorSpace);
    CGContextRestoreGState(theContext);
}
コード例 #21
0
ファイル: cgdrawcontext.cpp プロジェクト: UIKit0/vstgui
//-----------------------------------------------------------------------------
void CGDrawContext::drawCGImageRef (CGContextRef context, CGImageRef image, CGLayerRef layer, double bitmapScaleFactor, const CRect& inRect, const CPoint& inOffset, float alpha, CBitmap* bitmap)
{
    CRect rect (inRect);
    CPoint offset (inOffset);

    CGContextSetAlpha (context, (CGFloat)alpha*currentState.globalAlpha);

    CGRect dest;
    dest.origin.x = static_cast<CGFloat> (rect.left - offset.x);
    dest.origin.y = static_cast<CGFloat> (-(rect.top) - (bitmap->getHeight () - offset.y));
    dest.size.width = static_cast<CGFloat> (bitmap->getWidth ());
    dest.size.height = static_cast<CGFloat> (bitmap->getHeight ());

    CGRect clipRect;
    clipRect.origin.x = static_cast<CGFloat> (rect.left);
    clipRect.origin.y = static_cast<CGFloat> (-(rect.top) - rect.getHeight ());
    clipRect.size.width = static_cast<CGFloat> (rect.getWidth ());
    clipRect.size.height = static_cast<CGFloat> (rect.getHeight ());


    if (bitmapScaleFactor != 1.)
    {
        CGContextConcatCTM (context, CGAffineTransformMakeScale (static_cast<CGFloat> (1./bitmapScaleFactor), static_cast<CGFloat> (1./bitmapScaleFactor)));
        CGAffineTransform transform = CGAffineTransformMakeScale (static_cast<CGFloat> (bitmapScaleFactor), static_cast<CGFloat> (bitmapScaleFactor));
        clipRect.origin = CGPointApplyAffineTransform (clipRect.origin, transform);
        clipRect.size = CGSizeApplyAffineTransform (clipRect.size, transform);
        dest.origin = CGPointApplyAffineTransform (dest.origin, transform);
        dest.size = CGSizeApplyAffineTransform (dest.size, transform);
    }
    dest = pixelAlligned (dest);
    clipRect = pixelAlligned (clipRect);

    CGContextClipToRect (context, clipRect);

    if (layer)
    {
        CGContextDrawLayerInRect (context, dest, layer);
    }
    else
    {
        CGContextDrawImage (context, dest, image);
    }
}
コード例 #22
0
ファイル: TIPGradient.c プロジェクト: samiamwork/Questionable
void TIPGradientAxialFillRect( CGContextRef theContext, TIPGradientRef theGradient, CGRect theRect, float angle)
{
    CGPoint startPoint;
    CGPoint endPoint;

    TIPGradientFindEndpointsForRotation(theRect,angle,&startPoint,&endPoint);

    // CoreGraphics Calls
    CGContextSaveGState(theContext);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGShadingRef myCGShading = CGShadingCreateAxial(colorSpace,startPoint,endPoint,theGradient->gradientFunction,FALSE,FALSE);

    CGContextClipToRect(theContext,theRect);
    CGContextDrawShading(theContext,myCGShading);

    CGShadingRelease(myCGShading);
    CGColorSpaceRelease(colorSpace);
    CGContextRestoreGState(theContext);
}
コード例 #23
0
/* Draw the source PDF document into the context and then draw the stamp PDF document
on top of it. When drawing the stamp on top, place it along the diagonal from the lower
left corner to the upper right corner and center its media rect to the center of that
diagonal. */
void StampWithPDFDocument(CGContextRef context, 
			CGPDFDocumentRef sourcePDFDoc, 
			CGPDFDocumentRef stampFileDoc, CGRect stampMediaRect)
{
    CGRect pageRect;
    float angle;
    size_t i, numPages = CGPDFDocumentGetNumberOfPages(sourcePDFDoc);
    
    // Loop over document pages and stamp each one appropriately.
    for(i = 1 ; i <= numPages ; i++)
    {
		// Use the page rectangle of each page from the source to compute
		// the destination media box for each page and the location of
		// the stamp.
		CGRect pageRect = CGPDFDocumentGetMediaBox(sourcePDFDoc, i);
		CGContextBeginPage(context, &pageRect);
		CGContextSaveGState(context);
			// Clip to the media box of the page.
			CGContextClipToRect(context, pageRect);	    
			// First draw the content of the source document.
			CGContextDrawPDFDocument(context, pageRect, sourcePDFDoc, i);
			// Translate to center of destination rect, that is the center of 
			// the media box of content to draw on top of.
			CGContextTranslateCTM(context, 
				pageRect.size.width/2, pageRect.size.height/2);
			// Compute angle of the diagonal across the destination page.
			angle = atan(pageRect.size.height/pageRect.size.width);
			// Rotate by an amount so that drawn content goes along a diagonal
			// axis across the page.
			CGContextRotateCTM(context, angle);
			// Move the origin so that the media box of the PDF to stamp
			// is centered around center point of destination.
			CGContextTranslateCTM(context, 
			-stampMediaRect.size.width/2, 
			-stampMediaRect.size.height/2);
			// Now draw the document to stamp with on top of original content.
			CGContextDrawPDFDocument(context, stampMediaRect, 
					stampFileDoc, 1);
		CGContextRestoreGState(context);
		CGContextEndPage(context);
    }
}
コード例 #24
0
ファイル: ImageBufferCG.cpp プロジェクト: TigerLau1985/webkit
String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
{
    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));

    if (context().isAcceleratedContext())
        flushContext();

    RetainPtr<CFStringRef> uti = utiFromMIMEType(mimeType);
    ASSERT(uti);

    RefPtr<Uint8ClampedArray> premultipliedData;
    RetainPtr<CGImageRef> image;

    if (CFEqual(uti.get(), jpegUTI())) {
        // JPEGs don't have an alpha channel, so we have to manually composite on top of black.
        premultipliedData = getPremultipliedImageData(IntRect(IntPoint(0, 0), logicalSize()));
        if (!premultipliedData)
            return "data:,";

        RetainPtr<CGDataProviderRef> dataProvider;
        dataProvider = adoptCF(CGDataProviderCreateWithData(0, premultipliedData->data(), 4 * logicalSize().width() * logicalSize().height(), 0));
        if (!dataProvider)
            return "data:,";

        image = adoptCF(CGImageCreate(logicalSize().width(), logicalSize().height(), 8, 32, 4 * logicalSize().width(),
                                    deviceRGBColorSpaceRef(), kCGBitmapByteOrderDefault | kCGImageAlphaNoneSkipLast,
                                    dataProvider.get(), 0, false, kCGRenderingIntentDefault));
    } else if (m_resolutionScale == 1) {
        image = copyNativeImage(CopyBackingStore);
        image = createCroppedImageIfNecessary(image.get(), internalSize());
    } else {
        image = copyNativeImage(DontCopyBackingStore);
        RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
        CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
        CGContextClipToRect(context.get(), CGRectMake(0, 0, logicalSize().width(), logicalSize().height()));
        FloatSize imageSizeInUserSpace = scaleSizeToUserSpace(logicalSize(), m_data.backingStoreSize, internalSize());
        CGContextDrawImage(context.get(), CGRectMake(0, 0, imageSizeInUserSpace.width(), imageSizeInUserSpace.height()), image.get());
        image = adoptCF(CGBitmapContextCreateImage(context.get()));
    }

    return CGImageToDataURL(image.get(), mimeType, quality);
}
コード例 #25
0
ファイル: cgdrawcontext.cpp プロジェクト: DaniM/lyngo
//-----------------------------------------------------------------------------
CGContextRef CGDrawContext::beginCGContext (bool swapYAxis, bool integralOffset)
{
	if (cgContext)
	{
		CGContextSaveGState (cgContext);

		CGRect cgClipRect = CGRectMake (currentState.clipRect.left, currentState.clipRect.top, currentState.clipRect.width (), currentState.clipRect.height ());
		CGContextClipToRect (cgContext, cgClipRect);

		if (integralOffset)
			CGContextTranslateCTM (cgContext, round (currentState.offset.x), round (currentState.offset.y));
		else
			CGContextTranslateCTM (cgContext, currentState.offset.x, currentState.offset.y);

		if (!swapYAxis)
			CGContextScaleCTM (cgContext, 1, -1);
		return cgContext;
	}
	return 0;
}
コード例 #26
0
ファイル: ImageBufferCG.cpp プロジェクト: TigerLau1985/webkit
RefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior scaleBehavior) const
{
    RetainPtr<CGImageRef> image;
    if (m_resolutionScale == 1 || scaleBehavior == Unscaled) {
        image = copyNativeImage(copyBehavior);
        image = createCroppedImageIfNecessary(image.get(), internalSize());
    } else {
        image = copyNativeImage(DontCopyBackingStore);
        RetainPtr<CGContextRef> context = adoptCF(CGBitmapContextCreate(0, logicalSize().width(), logicalSize().height(), 8, 4 * logicalSize().width(), deviceRGBColorSpaceRef(), kCGImageAlphaPremultipliedLast));
        CGContextSetBlendMode(context.get(), kCGBlendModeCopy);
        CGContextClipToRect(context.get(), FloatRect(FloatPoint::zero(), logicalSize()));
        FloatSize imageSizeInUserSpace = scaleSizeToUserSpace(logicalSize(), m_data.backingStoreSize, internalSize());
        CGContextDrawImage(context.get(), FloatRect(FloatPoint::zero(), imageSizeInUserSpace), image.get());
        image = adoptCF(CGBitmapContextCreateImage(context.get()));
    }

    if (!image)
        return nullptr;

    return BitmapImage::create(image.get());
}
コード例 #27
0
ファイル: cgdrawcontext.cpp プロジェクト: UIKit0/vstgui
//-----------------------------------------------------------------------------
void CGDrawContext::fillRectWithBitmap (CBitmap* bitmap, const CRect& srcRect, const CRect& dstRect, float alpha)
{
    if (bitmap == 0 || alpha == 0.f || srcRect.isEmpty () || dstRect.isEmpty ())
        return;

    if (!(srcRect.left == 0 && srcRect.right == 0 && srcRect.right == bitmap->getWidth () && srcRect.bottom == bitmap->getHeight ()))
    {
        // CGContextDrawTiledImage does not work with parts of a bitmap
        CDrawContext::fillRectWithBitmap(bitmap, srcRect, dstRect, alpha);
        return;
    }

    IPlatformBitmap* platformBitmap = bitmap->getBestPlatformBitmapForScaleFactor (scaleFactor);
    CPoint bitmapSize = platformBitmap->getSize ();
    if (srcRect.right > bitmapSize.x || srcRect.bottom > bitmapSize.y)
        return;

    CGBitmap* cgBitmap = platformBitmap ? dynamic_cast<CGBitmap*> (platformBitmap) : 0;
    CGImageRef image = cgBitmap ? cgBitmap->getCGImage () : 0;
    if (image)
    {
        CGContextRef context = beginCGContext (false, true);
        if (context)
        {
            // TODO: Check if this works with retina images
            CGRect clipRect = CGRectFromCRect (dstRect);
            clipRect.origin.y = -(clipRect.origin.y) - clipRect.size.height;
            clipRect = pixelAlligned (clipRect);
            CGContextClipToRect (context, clipRect);

            CGRect r = {};
            r.size.width = CGImageGetWidth (image);
            r.size.height = CGImageGetHeight (image);

            CGContextDrawTiledImage (context, r, image);

            releaseCGContext (context);
        }
    }
}
コード例 #28
0
ファイル: cgdrawcontext.cpp プロジェクト: UIKit0/vstgui
//-----------------------------------------------------------------------------
CGContextRef CGDrawContext::beginCGContext (bool swapYAxis, bool integralOffset)
{
    if (cgContext)
    {
        if (currentState.clipRect.isEmpty ())
            return 0;

        CGContextSaveGState (cgContext);

        CGRect cgClipRect = CGRectFromCRect (currentState.clipRect);
        if (integralOffset)
            cgClipRect = pixelAlligned (cgClipRect);
        CGContextClipToRect (cgContext, cgClipRect);
#if DEBUG
        if (showClip)
        {
            CGContextSetRGBFillColor (cgContext, 1, 0, 0, 0.5);
            CGContextFillRect (cgContext, cgClipRect);
        }
#endif

        if (getCurrentTransform ().isInvariant () == false)
        {
            CGraphicsTransform t = getCurrentTransform ();
            if (integralOffset)
            {
                CGPoint p = pixelAlligned (CGPointFromCPoint (CPoint (t.dx, t.dy)));
                t.dx = p.x;
                t.dy = p.y;
            }
            CGContextConcatCTM (cgContext, QuartzGraphicsPath::createCGAffineTransform (t));
        }

        if (!swapYAxis)
            CGContextScaleCTM (cgContext, 1, -1);

        return cgContext;
    }
    return 0;
}
コード例 #29
0
ファイル: mac-gworld.cpp プロジェクト: 7sevenx7/snes9x
void DrawSubCGImage (CGContextRef ctx, CGImageRef image, CGRect src, CGRect dst)
{
    float	w = (float) CGImageGetWidth(image);
    float	h = (float) CGImageGetHeight(image);

	CGRect	drawRect = CGRectMake(0.0f, 0.0f, w, h);

	if (!CGRectEqualToRect(src, dst))
	{
		float	sx = CGRectGetWidth(dst)  / CGRectGetWidth(src);
		float	sy = CGRectGetHeight(dst) / CGRectGetHeight(src);
		float	dx = CGRectGetMinX(dst) - (CGRectGetMinX(src) * sx);
		float	dy = CGRectGetMinY(dst) - (CGRectGetMinY(src) * sy);

		drawRect = CGRectMake(dx, dy, w * sx, h * sy);
	}

	CGContextSaveGState(ctx);
	CGContextClipToRect(ctx, dst);
	CGContextDrawImage(ctx, drawRect, image);
	CGContextRestoreGState(ctx);
}
コード例 #30
0
ファイル: HIScrollingTextBox.c プロジェクト: 0b1kn00b/xcross
OSStatus ScrollingTextBoxDraw(CGContextRef context, const HIRect * bounds, const ScrollingTextBoxData * myData)
	{
	HIRect textBounds = { {kMargin, kMargin}, {bounds->size.width - kMargin - kMargin, myData->height} };
	HIRect clipBounds = CGRectInset(*bounds, kMargin + 1.0, kMargin + 1.0);

//
// If we're building on Panther (or later) then HIThemeDrawTextBox is available, else we use DrawThemeTextBox
//
#if PANTHER_BUILD
//
// Furthermore, if we're running on Panther then we can call HIThemeDrawTextBox else we call DrawThemeTextBox
//
	if (GetHIToolboxVersion() >= Panther_HIToolbox_Version)
		{
		CGContextClipToRect(context, clipBounds);

		HIThemeTextInfo textInfo = {0, kThemeStateActive, kScrollingTextBoxFontID, kHIThemeTextHorizontalFlushLeft, kHIThemeTextVerticalFlushTop, kHIThemeTextBoxOptionStronglyVertical, kHIThemeTextTruncationNone, 0, false};
		HIThemeDrawTextBox(myData->theText, &textBounds, &textInfo, context, kHIThemeOrientationNormal);
		}
	else
#endif
		{
		Rect QDTextBounds = HI2QDRECT(textBounds);
		Rect QDClipBounds = HI2QDRECT(clipBounds);

		RgnHandle saveClip = NewRgn();
		GetClip(saveClip);
		ClipRect(&QDClipBounds);

		DrawThemeTextBox(myData->theText, kScrollingTextBoxFontID, kThemeStateActive, true, &QDTextBounds, teJustLeft, context);

		SetClip(saveClip);
		DisposeRgn(saveClip);
		}

	return noErr;
	}