在說明牌視圖以前,咱們先看下View的實現,代碼以下:
java
/** * <p>Title: View.java</p> * <p>Description:視圖基類 </p> * <p>Copyright: Copyright (c) 2007</p> * @author Tunie * @date 2014年9月18日 * @version 1.0 */ public abstract class View extends JPanel { /** */ private static final long serialVersionUID = 2671149288739472345L; @Override protected void paintComponent(Graphics g) { super.paintComponent(g); refresh(g); } protected abstract void refresh(Graphics g); }
View繼承Jpanel並重寫了paintComponent方法,新增了一個refresh抽象方法,這意味着所示繼承了View的非抽象子類,必須實現該方法。至於爲什麼如此設計,我就不細說了,讀者自行體會。
ide
如今咱們着重看一下CardView的refresh方法,其實現代碼以下:設計
@Override protected void refresh(Graphics g) { calcImage(); Graphics2D g2d = (Graphics2D) g; g2d.drawImage(image, 0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT, null); }
沒有什麼特別的,主要要細看calcImage方法,代碼以下:code
private void calcImage() { image = new BufferedImage(DEFAULT_WIDTH, DEFAULT_HEIGHT, BufferedImage.TRANSLUCENT); Graphics2D graphics2d = image.createGraphics(); RoundRectangle2D rectangle2d = new RoundRectangle2D.Double(0, 0, DEFAULT_WIDTH-1, DEFAULT_HEIGHT-1 ,13 ,13); graphics2d.setColor(new Color(0xdddeee)); graphics2d.draw(rectangle2d); graphics2d.setColor(Color.white); RoundRectangle2D rectangle2d1 = new RoundRectangle2D.Double(0.5, 0.5, DEFAULT_WIDTH-2, DEFAULT_HEIGHT-2 ,12 ,12); graphics2d.fill(rectangle2d1); if(card.isNotKing()) { String cardColor = ColorType.getDescription(card.getColorType()) + ".png"; BufferedImage cardColorImage = AssertManager.getAssert(cardColor); int cardColorImageX = (DEFAULT_WIDTH - cardColorImage.getWidth())/2; int cardColorImageY = (DEFAULT_HEIGHT - cardColorImage.getHeight())/2; graphics2d.drawImage(cardColorImage, cardColorImageX, cardColorImageY, cardColorImage.getWidth(), cardColorImage.getHeight(), null); } int padding = 5; String type = card.getTypeImagePath(); BufferedImage typeImage = AssertManager.getAssert(type); graphics2d.drawImage(typeImage, padding, padding, typeImage.getWidth(), typeImage.getHeight(), null); String listtleCardColor = ColorType.getDescription(card.getColorType()) + "_little.png"; BufferedImage listtleCardColorImage = AssertManager.getAssert(listtleCardColor); int listtleCardColorImageX = padding + (typeImage.getWidth() - listtleCardColorImage.getWidth())/2; int listtleCardColorImageY = padding + typeImage.getHeight(); if(!card.isBigKing() && !card.isSmallKing() ) { graphics2d.drawImage(listtleCardColorImage, listtleCardColorImageX, listtleCardColorImageY, listtleCardColorImage.getWidth(), listtleCardColorImage.getHeight(), null); } graphics2d.translate(DEFAULT_WIDTH, DEFAULT_HEIGHT); graphics2d.rotate(Math.toRadians(180)); graphics2d.drawImage(typeImage, padding, padding, typeImage.getWidth(), typeImage.getHeight(), null); if(!card.isBigKing() && !card.isSmallKing() ) { graphics2d.drawImage(listtleCardColorImage, listtleCardColorImageX, listtleCardColorImageY, listtleCardColorImage.getWidth(), listtleCardColorImage.getHeight(), null); } }
看上去挺長的,其實重點在最後面的旋轉繪製處理,這個點明白了,這張牌的視圖實現就沒有問題了。繼承