public static boolean pngCaptcha(String randomStr, int width, int height, String file) { char[] strs = randomStr.toCharArray(); try (OutputStream out = new FileOutputStream(file)) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) bi.getGraphics(); AlphaComposite ac3; Color color; int len = strs.length; g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); for (int i = 0; i < 15; i++) { color = color(150, 250); g.setColor(color); g.drawOval(num(width), num(height), 5 + num(10), 5 + num(10)); } g.setFont(font); int h = height - ((height - font.getSize()) >> 1), w = width / len, size = w - font.getSize() + 1; for (int i = 0; i < len; i++) { // 指定透明度 ac3 = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f); g.setComposite(ac3); // 对每个字符都用随机颜色 color = new Color(20 + num(110), 30 + num(110), 30 + num(110)); g.setColor(color); g.drawString(strs[i] + "", (width - (len - i) * w) + size, h - 4); } ImageIO.write(bi, "png", out); out.flush(); return true; } catch (IOException e) { return false; } }
private static void addFragments( BidiRun run, char[] text, int start, int end, int fontStyle, FontPreferences fontPreferences, FontRenderContext fontRenderContext, @Nullable TabFragment tabFragment) { Font currentFont = null; int currentIndex = start; for (int i = start; i < end; i++) { char c = text[i]; if (c == '\t' && tabFragment != null) { assert run.level == 0; addTextFragmentIfNeeded( run, text, currentIndex, i, currentFont, fontRenderContext, run.isRtl()); run.fragments.add(tabFragment); currentFont = null; currentIndex = i + 1; } else { Font font = ComplementaryFontsRegistry.getFontAbleToDisplay(c, fontStyle, fontPreferences) .getFont(); if (!font.equals(currentFont)) { addTextFragmentIfNeeded( run, text, currentIndex, i, currentFont, fontRenderContext, run.isRtl()); currentFont = font; currentIndex = i; } } } addTextFragmentIfNeeded( run, text, currentIndex, end, currentFont, fontRenderContext, run.isRtl()); }
private static void fillStyledFontMap() { Font[] allFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); for (Font font : allFonts) { String name = font.getName(); Integer style = null; if (!SystemInfo.isAppleJvm) { style = FONT_NAME_TO_STYLE.get( name); // workaround with explicit fontName->style mapping doesn't work on Apple JVM } if (style == null) { if (!Patches.JDK_MAC_FONT_STYLE_BUG) continue; style = getFontStyle(name); } if (style != Font.PLAIN) { String familyName = font.getFamily(); Pair<String, Integer>[] entry = ourStyledFontMap.get(familyName); if (entry == null) { //noinspection unchecked entry = new Pair[4]; for (int i = 1; i < 4; i++) { entry[i] = Pair.create(familyName, i); } ourStyledFontMap.put(familyName, entry); } entry[style] = Pair.create(name, Font.PLAIN); } } }
public ExtendedTextField() { setFullScreenMode(true); setCommandListener(this); exit = new Command("Exit", Command.EXIT, 1); open = new Command("Open", Command.ITEM, 1); newFile = new Command("New", Command.ITEM, 2); save = new Command("Save", Command.ITEM, 3); saveAs = new Command("Save As", Command.ITEM, 4); eval = new Command("Eval", Command.ITEM, 5); output = new Command("Output", Command.ITEM, 6); cls = new Command("Clear", Command.ITEM, 7); addCommand(exit); addCommand(newFile); addCommand(open); addCommand(save); addCommand(saveAs); addCommand(eval); addCommand(output); addCommand(cls); new Thread(this).start(); // TODO: change font size? inputFont = Font.getDefaultFont(); inputWidth = getWidth(); inputHeight = inputFont.getHeight(); linesOnScreen = getHeight() / inputHeight; addNewLine(0); }
@Nullable Font getFontAbleToDisplay(LookupElementPresentation p) { String sampleString = p.getItemText() + p.getTailText() + p.getTypeText(); // assume a single font can display all lookup item chars Set<Font> fonts = ContainerUtil.newHashSet(); for (int i = 0; i < sampleString.length(); i++) { fonts.add( EditorUtil.fontForChar(sampleString.charAt(i), Font.PLAIN, myLookup.getEditor()) .getFont()); } eachFont: for (Font font : fonts) { if (font.equals(myNormalFont)) continue; for (int i = 0; i < sampleString.length(); i++) { if (!font.canDisplay(sampleString.charAt(i))) { continue eachFont; } } return font; } return null; }
public PlayPanel(Vector2f size, Vector2f position, RenderWindow window) { super(size, position); m_petriDish = new PetriDish(400.0f, new Vector2f(50.0f, 50.0f)); m_gameTime = Time.ZERO; m_showGps = false; // Load font Font m_timeFont = new Font(); try { InputStream istream = getClass().getResourceAsStream("/Resources/00TT.TTF"); m_timeFont.loadFromStream(istream); } catch (IOException ex) { // Failed to load font ex.printStackTrace(); } m_timeText = new Text("", m_timeFont, 30); m_timeText.setColor(Color.BLACK); m_timeText.setPosition(new Vector2f(10.0f, 5.0f)); m_fpsText = new Text("FPS: ", m_timeFont, 30); m_fpsText.setColor(Color.BLACK); m_fpsText.setPosition(new Vector2f(350.0f, 5.0f)); m_defaultView = window.getDefaultView(); m_currentView = new View(new Vector2f(400, 300), new Vector2f(800, 600)); m_zoom = 0; m_leftMouseHold = false; m_currentPan = m_holdMousePos = m_pan = Vector2i.ZERO; }
/** * Adds a Chunk. * * <p>This method is a hack to solve a problem I had with phrases that were split between chunks * in the wrong place. * * @param chunk a Chunk to add to the Phrase * @return true if adding the Chunk succeeded */ protected boolean addChunk(Chunk chunk) { Font f = chunk.getFont(); String c = chunk.getContent(); if (font != null && !font.isStandardFont()) { f = font.difference(chunk.getFont()); } if (size() > 0 && !chunk.hasAttributes()) { try { Chunk previous = (Chunk) get(size() - 1); if (!previous.hasAttributes() && (f == null || f.compareTo(previous.getFont()) == 0) && !"".equals(previous.getContent().trim()) && !"".equals(c.trim())) { previous.append(c); return true; } } catch (ClassCastException cce) { } } Chunk newChunk = new Chunk(c, f); newChunk.setAttributes(chunk.getAttributes()); if (newChunk.getHyphenation() == null) { newChunk.setHyphenation(hyphenation); } return super.add(newChunk); }
/** * Adds a <CODE>Chunk</CODE>, an <CODE>Anchor</CODE> or another <CODE>Phrase</CODE> to this <CODE> * Phrase</CODE>. * * @param index index at which the specified element is to be inserted * @param o an object of type <CODE>Chunk</CODE>, <CODE>Anchor</CODE> or <CODE>Phrase</CODE> * @throws ClassCastException when you try to add something that isn't a <CODE>Chunk</CODE>, * <CODE>Anchor</CODE> or <CODE>Phrase</CODE> */ public void add(int index, Object o) { if (o == null) return; try { Element element = (Element) o; if (element.type() == Element.CHUNK) { Chunk chunk = (Chunk) element; if (!font.isStandardFont()) { chunk.setFont(font.difference(chunk.getFont())); } if (hyphenation != null) { chunk.setHyphenation(hyphenation); } super.add(index, chunk); } else if (element.type() == Element.PHRASE || element.type() == Element.ANCHOR || element.type() == Element.ANNOTATION || element.type() == Element.TABLE || // line added by David Freels element.type() == Element.YMARK || element.type() == Element.MARKED) { super.add(index, element); } else { throw new ClassCastException(String.valueOf(element.type())); } } catch (ClassCastException cce) { throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage()); } }
@Override public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException { System.out.println("PageFormat: width=" + pf.getWidth() + ", height=" + pf.getHeight()); Logger.getGlobal().log(Level.INFO, "PageFormat {0}", pf); System.out.println("pageIndex " + pageIndex); Logger.getGlobal().log(Level.INFO, "pageIndex {0}", pageIndex); if (pageIndex == 0) { Graphics2D g2d = (Graphics2D) g; Font font = g2d.getFont(); g2d.setFont(font.deriveFont((float) fontSize)); g2d.translate(pf.getImageableX(), pf.getImageableY()); g2d.setColor(Color.black); int step = g2d.getFont().getSize(); step += step / 4; double y = paddingTop + g2d.getFont().getSize(); for (String s : printStringList) { Logger.getGlobal().log(Level.INFO, "printStringList: {0}", s); g2d.drawString(s, (float) paddingLeft, (float) y); y += step; } // g2d.fillRect(0, 0, 200, 200); return Printable.PAGE_EXISTS; } else { return Printable.NO_SUCH_PAGE; } }
public void setSelectedFont(Font font) { selectedFont = font; family = font.getFamily(); style = font.getStyle(); size = font.getSize(); preview.setFont(font); }
private JComponent createLogo() { NonOpaquePanel panel = new NonOpaquePanel(new BorderLayout()); ApplicationInfoEx app = ApplicationInfoEx.getInstanceEx(); JLabel logo = new JLabel(IconLoader.getIcon(app.getWelcomeScreenLogoUrl())); logo.setBorder(JBUI.Borders.empty(30, 0, 10, 0)); logo.setHorizontalAlignment(SwingConstants.CENTER); panel.add(logo, BorderLayout.NORTH); JLabel appName = new JLabel(ApplicationNamesInfo.getInstance().getFullProductName()); Font font = getProductFont(); appName.setForeground(JBColor.foreground()); appName.setFont(font.deriveFont(JBUI.scale(36f)).deriveFont(Font.PLAIN)); appName.setHorizontalAlignment(SwingConstants.CENTER); String appVersion = "Version " + app.getFullVersion(); if (app.isEAP() && app.getBuild().getBuildNumber() < Integer.MAX_VALUE) { appVersion += " (" + app.getBuild().asString() + ")"; } JLabel version = new JLabel(appVersion); version.setFont(getProductFont().deriveFont(JBUI.scale(16f))); version.setHorizontalAlignment(SwingConstants.CENTER); version.setForeground(Gray._128); panel.add(appName); panel.add(version, BorderLayout.SOUTH); panel.setBorder(JBUI.Borders.emptyBottom(20)); return panel; }
/** * Set the Font to use with the class * * @param f Font */ public void setFont(Font f) { font = f; fontname = f.getName(); fontstyle = f.getStyle(); fontsize = f.getSize(); parse = true; }
public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; String message = "Hello, World!"; Font f = new Font("Serif", Font.BOLD, 36); g2.setFont(f); FontRenderContext context = g2.getFontRenderContext(); Rectangle2D bounds = f.getStringBounds(message, context); double x = (getWidth() - bounds.getWidth()) / 2; double y = (getHeight() - bounds.getHeight()) / 2; double ascent = -bounds.getY(); double baseY = y + ascent; g2.drawString(message, (int) x, (int) baseY); g2.setPaint(Color.LIGHT_GRAY); g2.draw(new Line2D.Double(x, baseY, x + bounds.getWidth(), baseY)); Rectangle2D rect = new Rectangle2D.Double(x, y, bounds.getWidth(), bounds.getHeight()); g2.draw(rect); }
public Rectangle2D getBounds2D() { StringTokenizer tokens = new StringTokenizer(getRenderString(), "\n"); int noLines = tokens.countTokens(); double height = (theFont.getSize2D() * noLines) + 5; double width = 0; while (tokens.hasMoreTokens()) { double l = theFont.getSize2D() * tokens.nextToken().length() * (5.0 / 8.0); if (l > width) width = l; } double parX; double parY; if (parent instanceof State) { parX = ((State) parent).getX(); parY = ((State) parent).getY(); } else if (parent instanceof Transition) { parX = ((Transition) parent).getMiddle().getX(); // dummy parY = ((Transition) parent).getMiddle().getY(); // dummy } else { parX = 0; parY = 0; } double mx = parX + offsetX; double my = parY + offsetY - 10; double tx = parX + width + offsetX; double ty = parY + height + offsetY - 10; return new Rectangle2D.Double(mx, my, tx - mx, ty - my); }
public void workOutMinsAndMaxs() { StringTokenizer tokens = new StringTokenizer(getRenderString(), "\n"); int noLines = tokens.countTokens(); double height = (theFont.getSize2D() * noLines) + 5; double width = 0; while (tokens.hasMoreTokens()) { double l = theFont.getSize2D() * tokens.nextToken().length() * (5.0 / 8.0); if (l > width) width = l; } double parX; double parY; if (parent instanceof State) { parX = ((State) parent).getX(); parY = ((State) parent).getY(); } else if (parent instanceof Transition) { parX = ((Transition) parent).getMiddle().getX(); // dummy parY = ((Transition) parent).getMiddle().getY(); // dummy } else { parX = 0; parY = 0; } minX = parX + offsetX - 5; minY = parY + offsetY - 25; maxX = parX + width + offsetX + 5; maxY = parY + height + offsetY - 5; }
public static void bumpUpFontSize(Component widget, int bumps) { if (!UserPreferences.readLocalePref() .equals("ko")) { // HACK!!! refector with variable localeSupportsBold Font f = widget.getFont(); widget.setFont(new Font(f.getFamily(), f.getStyle(), f.getSize() + bumps)); } }
private static File findFileForFont(Font font, final boolean matchStyle) { final String normalizedFamilyName = font.getFamily().toLowerCase(Locale.getDefault()).replace(" ", ""); final int fontStyle = font.getStyle(); File[] files = new File(System.getProperty("user.home"), "Library/Fonts") .listFiles( new FilenameFilter() { @Override public boolean accept(File file, String name) { String normalizedName = name.toLowerCase(Locale.getDefault()); return normalizedName.startsWith(normalizedFamilyName) && (normalizedName.endsWith(".otf") || normalizedName.endsWith(".ttf")) && (!matchStyle || fontStyle == ComplementaryFontsRegistry.getFontStyle(name)); } }); if (files == null || files.length == 0) return null; // to make sure results are predictable we return first file in alphabetical order return Collections.min( Arrays.asList(files), new Comparator<File>() { @Override public int compare(File file1, File file2) { return file1.getName().compareTo(file2.getName()); } }); }
/** * Paints the graphic component * * @param g Graphic component */ public void paint(Graphics g) { if (environment != null) { Sudoku env = (Sudoku) environment; Board board = env.getBoard(); int n = SudokuLanguage.DIGITS; int sqrt_n = (int) (Math.sqrt(n) + 0.1); g.setColor(Color.lightGray); Font font = g.getFont(); g.setFont(new Font(font.getName(), font.getStyle(), 20)); for (int i = 0; i < n; i++) { int ci = getCanvasValue(i); if (i % sqrt_n == 0) { g.drawLine(ci, DRAW_AREA_SIZE + MARGIN, ci, MARGIN); g.drawLine(DRAW_AREA_SIZE + MARGIN, ci, MARGIN, ci); } for (int j = 0; j < n; j++) { int cj = getCanvasValue(j); int value = board.get(i, j); if (value > 0) { g.setColor(Color.black); g.drawString("" + value, cj + CELL_SIZE / 5, ci + CELL_SIZE); g.setColor(Color.lightGray); } } } g.drawLine(DRAW_AREA_SIZE + MARGIN, DRAW_AREA_SIZE + MARGIN, DRAW_AREA_SIZE + MARGIN, MARGIN); g.drawLine(DRAW_AREA_SIZE + MARGIN, DRAW_AREA_SIZE + MARGIN, MARGIN, DRAW_AREA_SIZE + MARGIN); } }
public static void main(String[] args) { final Display display = new Display(); final Shell shell = new Shell(display); shell.setLayout(new FillLayout()); final StyledText styledText = new StyledText(shell, SWT.WRAP | SWT.BORDER); styledText.setText(text); FontData data = display.getSystemFont().getFontData()[0]; Font font = new Font(display, data.getName(), 16, SWT.BOLD); styledText.setFont(font); styledText.setForeground(display.getSystemColor(SWT.COLOR_BLUE)); styledText.addListener( SWT.Resize, new Listener() { public void handleEvent(Event event) { Rectangle rect = styledText.getClientArea(); Image newImage = new Image(display, 1, Math.max(1, rect.height)); GC gc = new GC(newImage); gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE)); gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW)); gc.fillGradientRectangle(rect.x, rect.y, 1, rect.height, true); gc.dispose(); styledText.setBackgroundImage(newImage); if (oldImage != null) oldImage.dispose(); oldImage = newImage; } }); shell.setSize(700, 400); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } if (oldImage != null) oldImage.dispose(); font.dispose(); display.dispose(); }
/* * (non-Javadoc) * * @see org.math.plot.render.AbstractDrawer#drawStringRatio(java.lang.String, * double[], double, double, double) */ public void drawTextBase(String label, double... rC) { int[] sC = projection.screenProjectionBase(rC); // Corner offset adjustment : Text Offset is used Here FontRenderContext frc = comp2D.getFontRenderContext(); Font font1 = comp2D.getFont(); int x = sC[0]; int y = sC[1]; double w = font1.getStringBounds(label, frc).getWidth(); double h = font1.getSize2D(); x -= (int) (w * text_Eastoffset); y += (int) (h * text_Northoffset); int wc = (int) (w * FastMath.cos(text_angle) + h * FastMath.sin(text_angle)); int hc = (int) (h * FastMath.cos(text_angle) + w * FastMath.sin(text_angle)); if (!comp2D.hitClip(x, y, wc, hc)) { return; } if (text_angle != 0) { comp2D.rotate(text_angle, x + w / 2, y - h / 2); } String[] lines = label.split("\n"); for (int i = 0; i < lines.length; i++) { comp2D.drawString(lines[i], x, y); y += h; } // comp2D.drawString(label, x, y); if (text_angle != 0) { comp2D.rotate(-text_angle, x + w / 2, y - h / 2); } }
private int computeTextWidth(@NotNull Font font, final boolean mainTextOnly) { int result = 0; int baseSize = font.getSize(); boolean wasSmaller = false; for (int i = 0; i < myAttributes.size(); i++) { SimpleTextAttributes attributes = myAttributes.get(i); boolean isSmaller = attributes.isSmaller(); if (font.getStyle() != attributes.getFontStyle() || isSmaller != wasSmaller) { // derive font only if it is necessary font = font.deriveFont( attributes.getFontStyle(), isSmaller ? UIUtil.getFontSize(UIUtil.FontSize.SMALL) : baseSize); } wasSmaller = isSmaller; result += computeStringWidth(i, font); final int fixedWidth = myFragmentPadding.get(i); if (fixedWidth > 0 && result < fixedWidth) { result = fixedWidth; } if (mainTextOnly && myMainTextLastIndex >= 0 && i == myMainTextLastIndex) break; } return result; }
public Dimension getPreferredSize(int rows) { toolkit.lockAWT(); try { Dimension minSize = getMinimumSize(rows); if (items.isEmpty()) { return minSize; } if (!isDisplayable()) { return new Dimension(); } int maxItemWidth = minSize.width; Graphics2D gr = (Graphics2D) getGraphics(); FontRenderContext frc = gr.getFontRenderContext(); Font font = getFont(); for (int i = 0; i < items.size(); i++) { String item = getItem(i); int itemWidth = font.getStringBounds(item, frc).getBounds().width; if (itemWidth > maxItemWidth) { maxItemWidth = itemWidth; } } gr.dispose(); return new Dimension(maxItemWidth, minSize.height); } finally { toolkit.unlockAWT(); } }
/** * Sets the font that the receiver will use to paint textual information for the specified cell in * this item to the font specified by the argument, or to the default font for that kind of * control if the argument is null. * * @param index the column index * @param font the new font (or null) * @exception IllegalArgumentException * <ul> * <li>ERROR_INVALID_ARGUMENT - if the argument has been disposed * </ul> * * @exception SWTException * <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been disposed * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the thread that created the receiver * </ul> * * @since 3.0 */ public void setFont(int index, Font font) { checkWidget(); if (font != null && font.isDisposed()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } int count = Math.max(1, parent.getColumnCount()); if (0 > index || index > count - 1) return; if (cellFont == null) { if (font == null) return; cellFont = new Font[count]; } Font oldFont = cellFont[index]; if (oldFont == font) return; cellFont[index] = font; if (oldFont != null && oldFont.equals(font)) return; int modelIndex = parent.columnCount == 0 ? Table.FIRST_COLUMN : parent.columns[index].modelIndex; int /*long*/ fontHandle = font != null ? font.handle : 0; OS.gtk_list_store_set(parent.modelHandle, handle, modelIndex + Table.CELL_FONT, fontHandle, -1); /* * Bug in GTK. When using fixed-height-mode, * row changes do not cause the row to be repainted. The fix is to * invalidate the row when it is cleared. */ if ((parent.style & SWT.VIRTUAL) != 0) { if (OS.GTK_VERSION >= OS.VERSION(2, 3, 2) && OS.GTK_VERSION < OS.VERSION(2, 6, 3)) { redraw(); } } cached = true; if (font != null) { boolean customDraw = (parent.columnCount == 0) ? parent.firstCustomDraw : parent.columns[index].customDraw; if (!customDraw) { if ((parent.style & SWT.VIRTUAL) == 0) { int /*long*/ parentHandle = parent.handle; int /*long*/ column = 0; if (parent.columnCount > 0) { column = parent.columns[index].handle; } else { column = OS.gtk_tree_view_get_column(parentHandle, index); } if (column == 0) return; int /*long*/ textRenderer = parent.getTextRenderer(column); int /*long*/ imageRenderer = parent.getPixbufRenderer(column); OS.gtk_tree_view_column_set_cell_data_func( column, textRenderer, display.cellDataProc, parentHandle, 0); OS.gtk_tree_view_column_set_cell_data_func( column, imageRenderer, display.cellDataProc, parentHandle, 0); } if (parent.columnCount == 0) { parent.firstCustomDraw = true; } else { parent.columns[index].customDraw = true; } } } }
private boolean canDisplayImpl(char c) { if (USE_ALTERNATIVE_CAN_DISPLAY_PROCEDURE) { return myFont.createGlyphVector(DUMMY_CONTEXT, new char[] {c}).getGlyphCode(0) > 0; } else { return myFont.canDisplay(c); } }
public static void makeEmphasized(Component widget) { // Set to bold amd add color Font font = widget.getFont(); if (!UserPreferences.readLocalePref() .equals("ko")) // HACK!!! refector with variable localeSupportsBold widget.setFont(new Font(font.getFamily(), Font.BOLD, font.getSize())); widget.setForeground(UIProperties.emphasisColor); }
private static Font findFont(String name) { for (Font font : GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts()) { if (font.getName().equals(name)) { return font; } } return null; }
/** * Instantiate the class * * @param s String to parse. * @param f Font to use. */ public TextLine(String s, Font f) { this(s); font = f; if (font == null) return; fontname = f.getName(); fontstyle = f.getStyle(); fontsize = f.getSize(); }
protected void initFont() { myNormalFont = createFont(); myBoldFont = myNormalFont.deriveFont(Font.BOLD); myItalicFont = myNormalFont.deriveFont(Font.ITALIC); myBoldItalicFont = myBoldFont.deriveFont(Font.ITALIC); establishFontMetrics(); }
public FontCollector setDefaultFont(Font defaultFont) { mDefaultFont = defaultFont; if (defaultFont != null) { setFontFamily(defaultFont.getFontFamily()); setFontStyle(defaultFont.getFontStyle()); } return this; }
public Image colImage(int color) { Image img = Image.createImage(Font.getDefaultFont().getHeight(), Font.getDefaultFont().getHeight()); Graphics g = img.getGraphics(); g.setColor(color); g.fillRect(0, 0, img.getWidth(), img.getHeight()); return img; }