下面列出了org.eclipse.swt.widgets.Layout#org.eclipse.swt.graphics.GC 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a new painter for the given text viewer.
*
* @param textViewer
* the text viewer the painter should be attached to
*/
public IndentGuidePainter(ITextViewer textViewer) {
super();
fTextViewer = textViewer;
fTextWidget = textViewer.getTextWidget();
GC gc = new GC(fTextWidget);
gc.setAdvanced(true);
fIsAdvancedGraphicsPresent = gc.getAdvanced();
gc.dispose();
IPreferenceStore store = Activator.getDefault().getPreferenceStore();
lineAlpha = store.getInt(PreferenceConstants.LINE_ALPHA);
lineStyle = store.getInt(PreferenceConstants.LINE_STYLE);
lineWidth = store.getInt(PreferenceConstants.LINE_WIDTH);
lineShift = store.getInt(PreferenceConstants.LINE_SHIFT);
drawLeftEnd = store.getBoolean(PreferenceConstants.DRAW_LEFT_END);
drawBlankLine = store.getBoolean(PreferenceConstants.DRAW_BLANK_LINE);
skipCommentBlock = store
.getBoolean(PreferenceConstants.SKIP_COMMENT_BLOCK);
}
/**
* @see org.eclipse.swt.widgets.Composite#computeSize(int, int, boolean)
*/
@Override
public Point computeSize(final int wHint, final int hHint, final boolean changed) {
this.checkWidget();
boolean disposeGC = false;
if (this.gc == null || this.gc.isDisposed()) {
this.gc = new GC(this);
disposeGC = true;
}
final Point buttonSize = this.computeButtonSize();
int width = buttonSize.x;
int height = buttonSize.y;
if (this.text != null && this.text.trim().length() > 0) {
final Point textSize = this.gc.textExtent(this.text);
width += textSize.x + this.gap + 1;
}
width += 6;
height += 6;
if (disposeGC) {
this.gc.dispose();
}
return new Point(width, height);
}
private static String getShortStringTruncatedInTheEnd(GC gc, String text, int width) {
char[] chars = text.toCharArray();
int calcWidth = gc.stringExtent("...").x;
int index = 0;
int length = chars.length;
while (calcWidth < width && index < length) {
int step = gc.getCharWidth(chars[index]);
calcWidth += step;
if (calcWidth >= width) {
break;
}
index++;
}
if (index == length - 1) {
return text;
}
StringBuilder sb = new StringBuilder(index + 4);
if (index > 4) {
sb.append(text.substring(0, index - 4));
} else {
sb.append(text.substring(0, 1));
}
sb.append("...");
return sb.toString();
}
/**
* Sets the receiver's row header image. If the image is <code>null</code>
* none is shown in the header
*
* @param image
* the new image
* @throws org.eclipse.swt.SWTException
* <ul>
* <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed
* </li>
* <li>ERROR_THREAD_INVALID_ACCESS - if not called from the
* thread that created the receiver</li>
* </ul>
*/
public void setHeaderImage(Image image) {
checkWidget();
// if (text == null) SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (image != headerImage) {
GC gc = new GC(parent);
int oldWidth = parent.getRowHeaderRenderer().computeSize(gc,
SWT.DEFAULT, SWT.DEFAULT, this).x;
int oldHeight = parent.getRowHeaderRenderer().computeSize(gc,
SWT.DEFAULT, SWT.DEFAULT, this).y;
this.headerImage = image;
int newWidth = parent.getRowHeaderRenderer().computeSize(gc,
SWT.DEFAULT, SWT.DEFAULT, this).x;
int newHeight = parent.getRowHeaderRenderer().computeSize(gc,
SWT.DEFAULT, SWT.DEFAULT, this).y;
gc.dispose();
parent.recalculateRowHeaderWidth(this, oldWidth, newWidth);
parent.recalculateRowHeaderHeight(this, oldHeight, newHeight);
}
parent.redraw();
}
int drawLeftJustified(GC gc, boolean paint, List<DrawData> line, int y) {
int maxY = 0;
if (line.size() > 0) {
int startIndex = getStartIndex(line);
int x = bounds.x + paddingLeft;
for (int i = startIndex; i < line.size(); i++) {
DrawData drawData = line.get(i);
x = drawTextToken(gc, paint, y, x, drawData);
if (drawData.extent.y > maxY) {
maxY = drawData.extent.y;
}
}
}
return maxY;
}
@Override
public void run() {
if (file == null)
return;
log.trace("export product graph as image: {}", file);
ScalableRootEditPart editPart = (ScalableRootEditPart) editor.getGraphicalViewer().getRootEditPart();
IFigure rootFigure = editPart.getLayer(LayerConstants.PRINTABLE_LAYERS);
Rectangle bounds = rootFigure.getBounds();
Image img = new Image(null, bounds.width, bounds.height);
GC imageGC = new GC(img);
Graphics graphics = new SWTGraphics(imageGC);
rootFigure.paint(graphics);
ImageLoader imgLoader = new ImageLoader();
imgLoader.data = new ImageData[] { img.getImageData() };
imgLoader.save(file.getAbsolutePath(), SWT.IMAGE_PNG);
}
/**
* draw temporary labels for external nodes (and save their bounds for later)
*/
private List<Rectangle> drawTemporaryLabels(GC gc) {
final List<Rectangle> nodesExternalBounds = new ArrayList<>();
final Rectangle clip = GraphUtils.getClip(gc);
float px = clip.x + clip.width;
float py = clip.y + clip.height;
for (String currNE : endNodesExternal) {
final org.eclipse.swt.graphics.Point size = gc.stringExtent(currNE);
py -= size.y + 4;
final float rx = px - (size.x + 4);
final Rectangle b = new Rectangle(rx, py, size.x, size.y);
nodesExternalBounds.add(b);
// TODO string extent will be computed twice :(
GraphUtils.drawString(gc, currNE, b.x + b.width / 2, b.y + b.height / 2);
}
return nodesExternalBounds;
}
/**
* Draw a String in the drawing area, splitting it into multiple lines.
*
* @param gc gc
* @param rect drawing area
* @param s String to draw
* @param cellStyle cell style determing alignment
*/
private void drawCellStringMulti(GC gc, Rectangle rect, String s, ICellStyle cellStyle) {
int halign = TextRenderer.LEFT;
if (cellStyle.getHorizontalAlignment() == ITableViewState.HAlignment.RIGHT) {
halign = TextRenderer.RIGHT;
} else if (cellStyle.getHorizontalAlignment() == ITableViewState.HAlignment.CENTER) {
halign = TextRenderer.CENTER;
}
int valign = TextRenderer.TOP;
if (cellStyle.getVerticalAlignment() == ITableViewState.VAlignment.BOTTOM) {
valign = TextRenderer.BOTTOM;
} else if (cellStyle.getVerticalAlignment() == ITableViewState.VAlignment.CENTER) {
valign = TextRenderer.CENTER;
}
TextRenderer.renderText(gc, rect, true, false, s, halign, valign);
}
public Point computeSize(int wHint, int hHint, boolean changed) {
checkWidget();
int width = 0, height = 0;
String[] items = list.getItems();
GC gc = new GC(text);
int spacer = gc.stringExtent(" ").x; //$NON-NLS-1$
int textWidth = gc.stringExtent(text.getText()).x;
for (int i = 0; i < items.length; i++) {
textWidth = Math.max(gc.stringExtent(items[i]).x, textWidth);
}
gc.dispose();
Point textSize = text.computeSize(SWT.DEFAULT, SWT.DEFAULT, changed);
Point arrowSize = arrow.computeSize(SWT.DEFAULT, SWT.DEFAULT, changed);
Point listSize = list.computeSize(SWT.DEFAULT, SWT.DEFAULT, changed);
int borderWidth = getBorderWidth();
height = Math.max(textSize.y, arrowSize.y);
width = Math.max(textWidth + 2 * spacer + arrowSize.x + 2 * borderWidth, listSize.x);
if (wHint != SWT.DEFAULT)
width = wHint;
if (hHint != SWT.DEFAULT)
height = hHint;
return new Point(width + 2 * borderWidth, height + 2 * borderWidth);
}
private Point computeSizeOfTextAndImages() {
int width = 0, height = 0;
final boolean textISNotEmpty = getText() != null && !getText().equals("");
if (textISNotEmpty) {
final GC gc = new GC(this.parentBreadcrumb);
gc.setFont(this.parentBreadcrumb.getFont());
final Point extent = gc.stringExtent(getText());
gc.dispose();
width += extent.x;
height = extent.y;
}
final Point imageSize = computeMaxWidthAndHeightForImages(getImage(),
this.selectionImage, this.disabledImage);
if (imageSize.x != -1) {
width += imageSize.x;
height = Math.max(imageSize.y, height);
if (textISNotEmpty) {
width += MARGIN * 2;
}
}
width += MARGIN;
return new Point(width, height);
}
public static IMenuItemProvider autoResizeColumnMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem autoResizeColumns = new MenuItem(popupMenu, SWT.PUSH);
autoResizeColumns.setText("Auto resize column");
autoResizeColumns.setImage(GUIHelper.getImage("auto_resize"));
autoResizeColumns.setEnabled(true);
autoResizeColumns.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
int columnPosition = getNatEventData(event).getColumnPosition();
natTable.doCommand(new InitializeAutoResizeColumnsCommand(natTable, columnPosition, natTable.getConfigRegistry(), new GC(natTable)));
}
});
}
};
}
@Override
public Control createReadonlyControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayoutFactory.fillDefaults().numColumns(2).spacing(10, 0)
.margins(0, 0).applyTo(composite);
textPriceReadonly = new Text(composite, SWT.BORDER);
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER)
.grab(true, false).applyTo(textPriceReadonly);
textPriceReadonly.setText("");
labelPriceTotalReadonly = new Label(composite, SWT.NONE);
GC gc = new GC(labelPriceTotalReadonly);
GridDataFactory.fillDefaults().align(SWT.END, SWT.CENTER)
.hint(gc.textExtent(THIRD_COLUMN).x, SWT.DEFAULT)
.applyTo(labelPriceTotalReadonly);
gc.dispose();
labelPriceTotalReadonly.setText("0.0");
return composite;
// textPriceReadonly = new Text(parent, SWT.BORDER);
// textPriceReadonly.setEditable(false);
// return textPriceReadonly;
}
/**
* Create the background of the container
*/
private void createButtonsContainerBackground() {
buttonContainer.addListener(SWT.Resize, event -> {
final Rectangle rect = buttonContainer.getClientArea();
final Image image = new Image(getDisplay(), Math.max(1, rect.width), Math.max(1, rect.height));
final GC gc = new GC(image);
final Color grey = new Color(getDisplay(), 204, 204, 204);
gc.setForeground(grey);
gc.drawLine(0, rect.height - 1, rect.width, rect.height - 1);
grey.dispose();
gc.dispose();
buttonContainer.setBackgroundImage(image);
if (oldButtonContainerImage != null) {
oldButtonContainerImage.dispose();
}
oldButtonContainerImage = image;
});
SWTGraphicUtil.addDisposer(buttonContainer, oldButtonContainerImage);
}
/**
* Draws the ruler column.
*
* @param gc the GC to draw into
* @param visibleLines the visible model lines
*/
private void doPaint(GC gc, ILineRange visibleLines) {
Display display= fCachedTextWidget.getDisplay();
int lastLine = visibleLines.getStartLine() + visibleLines.getNumberOfLines();
int y = -JFaceTextUtil.getHiddenTopLinePixels(fCachedTextWidget);
if (mapMarks != null) {
for (int line= visibleLines.getStartLine(); line < lastLine; line++) {
int widgetLine= JFaceTextUtil.modelLineToWidgetLine(fCachedTextViewer, line);
if (widgetLine == -1)
continue;
int lineHeight= fCachedTextWidget.getLineHeight(fCachedTextWidget.getOffsetAtLine(widgetLine));
if (mapMarks != null && mapMarks.containsKey(line)) {
paintLine(line, mapMarks.get(line), y, lineHeight, gc, display);
}
y += lineHeight;
}
}
}
private void paintHeaderRow(GC gc, int x, int y, int[] columns,
final int h, int rowIndex, int[] colSpans) {
GridMargins margins = getMargins();
int col = 0;
for (int i = 0; i < colSpans.length; i++) {
final int colSpan = colSpans[i];
final int w = sum(columns, col, colSpan) + (colSpan - 1)
* margins.getHorizontalSpacing();
paintHeaderCell(gc, new Rectangle(x, y, w, h), rowIndex, col,
colSpan);
col += colSpan;
x += w + margins.getHorizontalSpacing();
}
}
public static IMenuItemProvider autoResizeColumnMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem autoResizeColumns = new MenuItem(popupMenu, SWT.PUSH);
autoResizeColumns.setText("Auto resize column");
autoResizeColumns.setImage(GUIHelper.getImage("auto_resize"));
autoResizeColumns.setEnabled(true);
autoResizeColumns.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
int columnPosition = getNatEventData(event).getColumnPosition();
natTable.doCommand(new InitializeAutoResizeColumnsCommand(natTable, columnPosition, natTable.getConfigRegistry(), new GC(natTable)));
}
});
}
};
}
/**
* {@inheritDoc}
*/
public Rectangle getTextBounds(GridItem item, boolean preferred) {
int x = leftMargin;
Rectangle bounds = new Rectangle(x, topMargin + textTopMargin, 0, 0);
GC gc = new GC(item.getParent());
gc.setFont(item.getFont(getColumn()));
Point size = gc.stringExtent(item.getText(getColumn()));
bounds.height = size.y;
if (preferred) {
bounds.width = size.x - 1;
} else {
bounds.width = getBounds().width - x - rightMargin;
}
gc.dispose();
return bounds;
}
@Override
protected AbstractControllableShape createControllableShape1(
Canvas canvas) {
return new AbstractControllableShape(canvas) {
@Override
public void createControlPoints() {
// the ellipse does not have any control points
}
@Override
public Ellipse createGeometry() {
double w5 = getCanvas().getClientArea().width / 5;
double h5 = getCanvas().getClientArea().height / 5;
return new Ellipse(w5, h5, 3 * w5, 3 * h5);
}
@Override
public void drawShape(GC gc) {
Ellipse ellipse = createGeometry();
gc.drawOval((int) ellipse.getX(), (int) ellipse.getY(),
(int) ellipse.getWidth(), (int) ellipse.getHeight());
}
};
}
public static IMenuItemProvider autoResizeAllSelectedColumnMenuItemProvider() {
return new IMenuItemProvider() {
public void addMenuItem(final NatTable natTable, final Menu popupMenu) {
MenuItem autoResizeColumns = new MenuItem(popupMenu, SWT.PUSH);
autoResizeColumns.setText("Auto resize all selected columns");
autoResizeColumns.setEnabled(true);
autoResizeColumns.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
int columnPosition = getNatEventData(event).getColumnPosition();
natTable.doCommand(new InitializeAutoResizeColumnsCommand(natTable, columnPosition, natTable.getConfigRegistry(), new GC(natTable)));
}
});
}
};
}
private AutoCloseable configGC(final GC gc) {
final int lineStyle = gc.getLineStyle();
final int alpha = gc.getAlpha();
final int[] lineDash = gc.getLineDash();
final Color foreground = gc.getForeground();
final Color background = gc.getBackground();
gc.setForeground(this.indentGuide.getColor(styledText));
gc.setBackground(styledText.getBackground());
gc.setAlpha(this.indentGuide.getTransparency());
gc.setLineStyle(SWT.LINE_CUSTOM);
gc.setLineDash(new int[] { 1, 2 });
return new AutoCloseable() {
@Override
public void close() throws Exception {
gc.setForeground(foreground);
gc.setBackground(background);
gc.setAlpha(alpha);
gc.setLineStyle(lineStyle);
gc.setLineDash(lineDash);
}
};
}
private void drawTimeGraphEntry(GC gc, long time0, long selectedTime, Rectangle rect, boolean selected, double pixelsPerNanoSec, Rectangle stateRect, Iterator<ITimeEvent> iterator) {
int lastX = -1;
fLastTransparentX = -1;
while (iterator.hasNext()) {
ITimeEvent event = iterator.next();
int x = SaturatedArithmetic.add(rect.x, (int) ((event.getTime() - time0) * pixelsPerNanoSec));
int xEnd = SaturatedArithmetic.add(rect.x, (int) ((event.getTime() + event.getDuration() - time0) * pixelsPerNanoSec));
if (x >= rect.x + rect.width || xEnd < rect.x) {
// event is out of bounds
continue;
}
xEnd = Math.min(rect.x + rect.width, xEnd);
stateRect.x = Math.max(rect.x, x);
stateRect.width = Math.max(1, xEnd - stateRect.x + 1);
if (stateRect.x < lastX) {
stateRect.width -= (lastX - stateRect.x);
if (stateRect.width > 0) {
stateRect.x = lastX;
} else {
stateRect.width = 0;
}
}
boolean timeSelected = selectedTime >= event.getTime() && selectedTime < event.getTime() + event.getDuration();
if (drawState(getColorScheme(), event, stateRect, gc, selected, timeSelected)) {
lastX = stateRect.x + stateRect.width;
}
}
}
/**
* Creates a new instance.
*
* @param gc the graphics context.
*/
public SWTGraphics2D(GC gc) {
super();
this.gc = gc;
this.hints = new RenderingHints(null);
this.composite = AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f);
setStroke(new BasicStroke());
}
public String getSpaceByWidth(int width) {
GC gc = new GC(Display.getDefault());
int spaceWidth = gc.getAdvanceWidth(' ');
gc.dispose();
int spacecount = width / spaceWidth;
StringBuilder b = new StringBuilder();
while (spacecount-- > 0) {
b.append(" ");
}
return b.toString();
}
public static void drawPie(GC gc,int x, int y,int width,int height,int percent) {
Color background = gc.getBackground();
gc.setForeground(Colors.blue);
int angle = (percent * 360) / 100;
if(angle<4)
angle = 0; // workaround fillArc rendering bug
gc.setBackground(Colors.white);
gc.fillArc(x,y,width,height,0,360);
gc.setBackground(background);
gc.fillArc(x,y,width,height,90,angle*-1);
gc.drawOval(x , y , width-1, height-1);
}
private void drawBackground(final GC gc, final int width, final int height) {
gc.setForeground(START_GRADIENT_COLOR);
gc.setBackground(END_GRADIENT_COLOR);
gc.fillGradientRectangle(0, 0, width, height, true);
if (hasBorder) {
gc.setForeground(BORDER_COLOR);
gc.drawRectangle(0, 0, width - 1, height - 1);
}
}
@Override
public Image getLegendImage(int imageHeight, int imageWidth, @NonNull Long id) {
/*
* If series exists in chart, then image legend match that series. Image will
* make sense if series exists in chart. If it does not exists, an image will
* still be created.
*/
OutputElementStyle appearance = fChartViewer.getSeriesStyle(id);
BaseXYPresentationProvider presProvider = fChartViewer.getPresentationProvider();
RGBAColor rgb = presProvider.getColorStyleOrDefault(appearance, StyleProperties.COLOR, DEFAULT_COLOR);
Color lineColor = new Color(Display.getDefault(), rgb.getRed(), rgb.getGreen(), rgb.getBlue());
Color background = Display.getDefault().getSystemColor(SWT.COLOR_WHITE);
PaletteData palette = new PaletteData(background.getRGB(), lineColor.getRGB());
ImageData imageData = new ImageData(imageWidth, imageHeight, 8, palette);
imageData.transparentPixel = 0;
Image image = new Image(Display.getDefault(), imageData);
GC gc = new GC(image);
gc.setBackground(background);
gc.fillRectangle(0, 0, imageWidth, imageHeight);
drawStyleLine(gc, lineColor, imageWidth, imageHeight, appearance);
drawStyledDot(gc, lineColor, imageWidth, imageHeight, appearance);
gc.dispose();
lineColor.dispose();
return image;
}
private void drawMarker( GC gc, int x, int maxy ) {
int[] triangle =
new int[] {
LEFT + MARGIN + x * fontwidth + offset.x, TOP - 4, LEFT + MARGIN + x * fontwidth + offset.x + 3,
TOP + 1, LEFT + MARGIN + x * fontwidth + offset.x - 3, TOP + 1 };
gc.fillPolygon( triangle );
gc.drawPolygon( triangle );
gc
.drawLine(
LEFT + MARGIN + x * fontwidth + offset.x, TOP + 1, LEFT + MARGIN + x * fontwidth + offset.x, maxy );
}
@Override
public int draw(GC gc, long nanosec, Rectangle rect) {
String stime;
synchronized (HOURS_FORMAT) {
stime = HOURS_FORMAT.format(new Date(nanosec / MILLISEC_IN_NS));
}
return Utils.drawText(gc, stime, rect, true);
}
@Override
protected void drawLabel(GC gc) {
Rectangle bounds = getBounds();
RGBAColor backgroundColor = getBackgroundColor();
if (fLabel != null && !fLabel.isEmpty() && bounds.width > bounds.height) {
gc.setForeground(Utils.getDistinctColor(RGBAUtil.fromRGBAColor(backgroundColor).rgb));
Utils.drawText(gc, fLabel, bounds.x, bounds.y, bounds.width, bounds.height, true, true);
}
}
public Parameters(GC gc, Color styledTextForeground, Point size,
int lineCount, int marginCols, Color marginColor, int spacing, int imageHeight, Transform transform,
Image tmpImage) {
this.gc = gc;
this.styledTextForeground = styledTextForeground;
this.size = size;
this.lineCount = lineCount;
this.marginCols = marginCols;
this.marginColor = marginColor;
this.spacing = spacing;
this.imageHeight = imageHeight;
this.transform = transform;
this.tmpImage = tmpImage;
}